Como Ler Metadados de Imagem do OneNote em Python

Como Ler Metadados de Imagem do OneNote em Python

Cada nó Image em um documento OneNote contém metadados juntamente com os bytes brutos dos pixels: o nome de arquivo original, as dimensões de exibição (largura e altura em pontos), o texto alternativo para acessibilidade e, opcionalmente, um URL de hiperlink se a imagem estiver vinculada. O Aspose.Note FOSS para Python expõe todos esses campos através da classe Image.


Pré-requisitos

pip install aspose-note

Propriedades da Imagem

PropriedadeTipoDescrição
img.BytesbytesDados brutos da imagem. Gravar no disco com open(name, "wb").write(img.Bytes).
img.FileNamestr | NoneNome de arquivo original armazenado no arquivo .one. None se não armazenado.
img.Widthfloat | NoneLargura de exibição em pontos. None se não armazenada.
img.Heightfloat | NoneAltura de exibição em pontos. None se não armazenada.
img.AlternativeTextDescriptionstr | NoneCorpo do texto alternativo de acessibilidade. None se não definido.
img.AlternativeTextTitlestr | NoneTítulo do texto alternativo de acessibilidade. None se não definido.
img.HyperlinkUrlstr | NoneURL se a imagem for um hyperlink clicável. None se não houver link.
img.Tagslist[NoteTag]Tags do OneNote anexadas a esta imagem (estrela, caixa de seleção, etc.).

Etapa 1: Carregar o Documento e Encontrar Imagens

from aspose.note import Document, Image

doc = Document("MyNotes.one")
images = doc.GetChildNodes(Image)
print(f"Found {len(images)} image(s)")

Etapa 2: Ler Metadados de Cada Imagem

Proteja todos os campos anuláveis com is not None antes de usar:

from aspose.note import Document, Image

doc = Document("MyNotes.one")

for i, img in enumerate(doc.GetChildNodes(Image), start=1):
    print(f"\nImage {i}:")
    print(f"  Filename:    {img.FileName or '(no filename)'}")
    print(f"  Size:        {img.Bytes and len(img.Bytes):,} bytes")

    if img.Width is not None and img.Height is not None:
        print(f"  Dimensions:  {img.Width:.1f} × {img.Height:.1f} pts")

    if img.AlternativeTextDescription:
        print(f"  Alt text:    {img.AlternativeTextDescription}")

    if img.HyperlinkUrl:
        print(f"  Hyperlink:   {img.HyperlinkUrl}")

    if img.Tags:
        for tag in img.Tags:
            print(f"  Tag:         {tag.Label or tag.Icon}")

Exemplo Completo: Salvar Imagens com Relatório de Metadados

from pathlib import Path
from aspose.note import Document, Image

def report_and_save_images(one_path: str, out_dir: str = "images") -> None:
    doc = Document(one_path)
    images = doc.GetChildNodes(Image)
    if not images:
        print("No images found.")
        return

    out = Path(out_dir)
    out.mkdir(exist_ok=True)

    for i, img in enumerate(images, start=1):
        # Determine save name
        name = img.FileName or f"image_{i}.bin"
        dest = out / name

        # Save bytes
        dest.write_bytes(img.Bytes)

        # Report metadata
        dims = (
            f"{img.Width:.0f}×{img.Height:.0f}pts"
            if img.Width is not None and img.Height is not None
            else "unknown size"
        )
        alt = img.AlternativeTextDescription or ""
        link = img.HyperlinkUrl or ""

        print(f"  [{i}] {name}  {dims}"
              + (f"  alt='{alt}'" if alt else "")
              + (f"  url={link}" if link else ""))

    print(f"\nSaved {len(images)} image(s) to '{out_dir}/'")

report_and_save_images("MyNotes.one")

Filtrar Imagens por Propriedade

Imagens com hiperlinks

from aspose.note import Document, Image

doc = Document("MyNotes.one")
linked = [img for img in doc.GetChildNodes(Image) if img.HyperlinkUrl]
for img in linked:
    print(f"{img.FileName or 'image'}{img.HyperlinkUrl}")

Imagens com texto alternativo

from aspose.note import Document, Image

doc = Document("MyNotes.one")
with_alt = [img for img in doc.GetChildNodes(Image) if img.AlternativeTextDescription]
for img in with_alt:
    print(f"{img.FileName}: {img.AlternativeTextDescription}")

Notas

  • img.Bytes está sempre presente (retorna b"" para imagens ilegíveis, nunca None). Verifique len(img.Bytes) > 0 antes de salvar.
  • img.AlternativeTextTitle pode ser None se o documento de origem não definir um título. Use img.AlternativeTextDescription como alternativa.
  • As dimensões estão em points (1 point = 1/72 polegada), correspondendo às convenções do PowerPoint e PDF.

Veja Também

 Português