Imágenes y Archivos Adjuntos — Aspose.Note FOSS para Python

Aspose.Note FOSS for Python gives direct access to both embedded images and attached files stored inside OneNote .one archivos de sección. El contenido se expone a través del Image y AttachedFile tipos de nodo.


Extrayendo imágenes

Cada imagen en un documento de OneNote está representada por un Image nodo. Utilice GetChildNodes(Image) para recuperar todas las imágenes del documento de forma 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)")

Propiedades de la imagen

PropiedadTipoDescripción
FileName`strNone`
BytesbytesDatos de imagen sin procesar (el formato coincide con el original, p. ej., PNG, JPEG)
Width`floatNone`
Height`floatNone`
AlternativeTextTitle`strNone`
AlternativeTextDescription`strNone`
HyperlinkUrl`strNone`
Tagslist[NoteTag]Etiquetas de OneNote adjuntas a esta imagen

Guardar imágenes con nombres de archivo seguros

Cuándo FileName es None o contiene caracteres inseguros para el sistema de archivos, sanea antes de guardar:

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)

Extraer imágenes por 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)

Inspeccionar texto alternativo y hipervínculos de la imagen

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)

Detectar formato de archivo de imagen a partir de bytes

Python’s imghdr módulo (Python ≤ 3.12) o el struct el módulo puede detectar el formato de imagen a partir de los primeros 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)

Extrayendo archivos adjuntos

Los archivos adjuntos incrustados se almacenan como AttachedFile nodos:

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)")

Propiedades de AttachedFile

PropiedadTipoDescripción
FileName`strNone`
BytesbytesContenido bruto del archivo
Tagslist[NoteTag]Etiquetas de OneNote adjuntas a este nodo

Inspeccionar etiquetas en imágenes y adjuntos

Ambos Image y AttachedFile Los nodos admiten etiquetas 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}")

Resumen: Image vs AttachedFile

FuncionalidadImageAttachedFile
FileNameSí (nombre original de la imagen)Sí (nombre original del archivo)
BytesBytes de imagen sin procesarBytes de archivo sin procesar
Width / HeightSí (dimensiones renderizadas)No
AlternativeTextTitle/DescriptionNo
HyperlinkUrlNo
Tags
Replace(node) métodoNo

Consejos

  • Siempre protege contra None nombres de archivo. img.FileName es None cuando el archivo no tenía nombre en el documento fuente.
  • img.Bytes nunca es None y siempre es el contenido binario sin procesar; puede ser de cero bytes para imágenes de marcador de posición.
  • Usar Page.GetChildNodes(Image) en lugar de Document.GetChildNodes(Image) para limitar la extracción a una sola página.
  • El Image.Replace(image) el método reemplaza el contenido de un nodo de imagen con otro en memoria; guardar de nuevo en .one no es compatible.

Ver también

 Español