Imatges i fitxers adjunts — Aspose.Note FOSS per a Python

Aspose.Note FOSS for Python gives direct access to both embedded images and attached files stored inside OneNote .one fitxers de secció. El contingut s’exposa a través del Image i AttachedFile tipus de node.


Extracció d’imatges

Cada imatge en un document de OneNote està representada per un Image node. Utilitzeu GetChildNodes(Image) per recuperar totes les imatges del document de manera recursiva:

from aspose.note import Document, Image

doc = Document("MyNotes.one")
for i, img in enumerate(doc.GetChildNodes(Image), start=1):
    filename = img.FileName or f"image_{i}.bin"
    with open(filename, "wb") as f:
        f.write(img.Bytes)
    print(f"Saved: {filename}  ({img.Width} x {img.Height} pts)")

Propietats de la imatge

PropietatTipusDescripció
FileName`strNone`
BytesbytesDades d’imatge en brut (el format coincideix amb l’original, p. ex. PNG, JPEG)
Width`floatNone`
Height`floatNone`
AlternativeTextTitle`strNone`
AlternativeTextDescription`strNone`
HyperlinkUrl`strNone`
Tagslist[NoteTag]Etiquetes de OneNote adjuntes a aquesta imatge

Desa les imatges amb noms de fitxer segurs

Quan FileName és None o conté caràcters insegurs per al sistema de fitxers, neteja abans de desar:

import re
from aspose.note import Document, Image

def safe_name(name: str | None, fallback: str) -> str:
    if not name:
        return fallback
    return re.sub(r'[<>:"/\\|?*]', "_", name)

doc = Document("MyNotes.one")
for i, img in enumerate(doc.GetChildNodes(Image), start=1):
    name = safe_name(img.FileName, f"image_{i}.bin")
    with open(name, "wb") as f:
        f.write(img.Bytes)

Extracció d’imatges per pàgina

from aspose.note import Document, Page, Image

doc = Document("MyNotes.one")
for page_num, page in enumerate(doc.GetChildNodes(Page), start=1):
    images = page.GetChildNodes(Image)
    print(f"Page {page_num}: {len(images)} image(s)")
    for i, img in enumerate(images, start=1):
        filename = f"page{page_num}_img{i}.bin"
        with open(filename, "wb") as f:
            f.write(img.Bytes)

Inspeccioneu el text alternatiu de les imatges i els hiperenllaços

from aspose.note import Document, Image

doc = Document("MyNotes.one")
for img in doc.GetChildNodes(Image):
    if img.AlternativeTextTitle:
        print("Alt title:", img.AlternativeTextTitle)
    if img.AlternativeTextDescription:
        print("Alt desc:", img.AlternativeTextDescription)
    if img.HyperlinkUrl:
        print("Linked to:", img.HyperlinkUrl)

Detecta el format de fitxer d’imatge a partir dels bytes

Python’s imghdr mòdul (Python ≤ 3.12) o el struct el mòdul pot detectar el format d’imatge a partir dels primers bytes:

from aspose.note import Document, Image

doc = Document("MyNotes.one")
for img in doc.GetChildNodes(Image):
    b = img.Bytes
    if b[:4] == b'\x89PNG':
        fmt = "png"
    elif b[:2] == b'\xff\xd8':
        fmt = "jpeg"
    elif b[:4] == b'GIF8':
        fmt = "gif"
    elif b[:2] in (b'BM',):
        fmt = "bmp"
    else:
        fmt = "bin"
    name = (img.FileName or f"image.{fmt}").rsplit(".", 1)[0] + f".{fmt}"
    with open(name, "wb") as f:
        f.write(b)

Extracció de fitxers adjunts

Els fitxers adjunts incrustats s’emmagatzemen com a AttachedFile nodes:

from aspose.note import Document, AttachedFile

doc = Document("NotesWithAttachments.one")
for i, af in enumerate(doc.GetChildNodes(AttachedFile), start=1):
    filename = af.FileName or f"attachment_{i}.bin"
    with open(filename, "wb") as f:
        f.write(af.Bytes)
    print(f"Saved attachment: {filename}  ({len(af.Bytes):,} bytes)")

Propietats d’AttachedFile

PropietatTipusDescripció
FileName`strNone`
BytesbytesContingut brut del fitxer
Tagslist[NoteTag]Etiquetes OneNote adjuntes a aquest node

Inspeccioneu les etiquetes a les imatges i als fitxers adjunts

Ambdós Image i AttachedFile els nodes admeten etiquetes de OneNote:

from aspose.note import Document, Image, AttachedFile

doc = Document("MyNotes.one")

for img in doc.GetChildNodes(Image):
    for tag in img.Tags:
        print(f"Image tag: {tag.Label}  completedTime={tag.CompletedTime}")

for af in doc.GetChildNodes(AttachedFile):
    for tag in af.Tags:
        print(f"Attachment tag: {tag.Label}  completedTime={tag.CompletedTime}")

Resum: Image vs AttachedFile

FuncionalitatImageAttachedFile
FileNameSí (nom original de la imatge)Sí (nom original del fitxer)
BytesBytes d’imatge en brutBytes de fitxer en brut
Width / HeightSí (dimensions renderitzades)No
AlternativeTextTitle/DescriptionNo
HyperlinkUrlNo
Tags
Replace(node) mètodeNo

Consells

  • Sempre protegeix contra None noms de fitxer. img.FileName és None quan el fitxer no tenia nom al document d’origen.
  • img.Bytes mai no és None i sempre és el contingut binari cru; pot ser de zero bytes per a imatges de marcador de posició.
  • Utilitza Page.GetChildNodes(Image) en lloc de Document.GetChildNodes(Image) per limitar l’extracció a una sola pàgina.
  • El Image.Replace(image) el mètode substitueix el contingut d’un node d’imatge per un altre in-memory; desar de nou a .one no és compatible.

Vegeu també

 Català