Cách Đọc Siêu Dữ Liệu Hình Ảnh từ OneNote bằng Python

Cách Đọc Siêu Dữ Liệu Hình Ảnh từ OneNote bằng Python

Mỗi nút Image trong tài liệu OneNote chứa siêu dữ liệu cùng với các byte pixel thô: tên tệp gốc, kích thước hiển thị (chiều rộng và chiều cao tính bằng điểm), văn bản thay thế cho khả năng truy cập, và tùy chọn một URL siêu liên kết nếu hình ảnh được liên kết. Aspose.Note FOSS cho Python cung cấp tất cả các trường này thông qua lớp Image.


Điều kiện tiên quyết

pip install aspose-note

Thuộc tính hình ảnh

PropertyTypeDescription
img.BytesbytesDữ liệu hình ảnh thô. Ghi vào đĩa bằng open(name, "wb").write(img.Bytes).
img.FileNamestr | NoneTên tệp gốc được lưu trong tệp .one. None nếu không được lưu.
img.Widthfloat | NoneChiều rộng hiển thị tính bằng điểm. None nếu không được lưu.
img.Heightfloat | NoneChiều cao hiển thị tính bằng điểm. None nếu không được lưu.
img.AlternativeTextDescriptionstr | NoneNội dung văn bản thay thế cho khả năng truy cập. None nếu chưa được đặt.
img.AlternativeTextTitlestr | NoneTiêu đề văn bản thay thế cho khả năng truy cập. None nếu chưa được đặt.
img.HyperlinkUrlstr | NoneURL nếu hình ảnh là liên kết có thể nhấp. None nếu không được liên kết.
img.Tagslist[NoteTag]Các thẻ OneNote được gắn vào hình ảnh này (ngôi sao, hộp kiểm, v.v.).

Bước 1: Tải tài liệu và tìm hình ảnh

from aspose.note import Document, Image

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

Bước 2: Đọc siêu dữ liệu cho mỗi hình ảnh

Bảo vệ tất cả các trường có thể null bằng is not None trước khi sử dụng:

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

Ví dụ hoàn chỉnh: Lưu hình ảnh với báo cáo siêu dữ liệu

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

Lọc hình ảnh theo thuộc tính

Hình ảnh có siêu liên kết

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

Hình ảnh có văn bản thay thế

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

Ghi chú

  • img.Bytes luôn có mặt (trả về b"" cho các hình ảnh không đọc được, không bao giờ None). Kiểm tra len(img.Bytes) > 0 trước khi lưu.
  • img.AlternativeTextTitle có thể là None nếu tài liệu nguồn không đặt tiêu đề. Sử dụng img.AlternativeTextDescription làm dự phòng.
  • Kích thước được tính bằng points (1 point = 1/72 inch), phù hợp với quy ước của PowerPoint và PDF.

Xem thêm

 Tiếng Việt