from __future__ import annotations import hashlib from dataclasses import dataclass from pathlib import Path from urllib.parse import quote, unquote, urlsplit, urlunsplit from .file_versions import atomic_write from .document_resources import analyze_document, apply_source_edits, resolve_local_reference IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg", ".tif", ".tiff"} def relocate_images(source: str, original: Path, target: Path) -> str: plan = plan_image_relocation(source, original, target) for destination, data in plan.files.items(): if not destination.exists(): atomic_write(destination, data) return plan.source def store_image(document: Path, data: bytes, suffix: str = ".png", label: str = "图片") -> str: suffix = suffix.lower() if suffix not in IMAGE_SUFFIXES or not data: raise ValueError("不支持的图片或图片内容为空") folder = document.parent / (document.stem + ".assets") digest = hashlib.sha256(data).hexdigest()[:24] target = folder / (digest + suffix) if not target.exists(): atomic_write(target, data) relative = quote(target.relative_to(document.parent).as_posix(), safe="/") label = label.replace("\\", "\\\\").replace("[", "\\[").replace("]", "\\]").replace("\n", " ") return f"![{label}]({relative})" def image_files(mime: object) -> list[Path]: if not mime.hasUrls(): return [] urls = mime.urls() paths = [Path(url.toLocalFile()) for url in urls if url.isLocalFile()] return paths if len(paths) == len(urls) and all(p.suffix.lower() in IMAGE_SUFFIXES and p.is_file() for p in paths) else [] def image_markdown(mime: object, document: Path) -> str | None: files = image_files(mime) if files: return "\n".join(store_image(document, p.read_bytes(), p.suffix, p.stem) for p in files) if mime.hasImage(): from PySide6.QtCore import QBuffer, QByteArray, QIODevice from PySide6.QtGui import QImage, QPixmap data = mime.imageData() picture = data.toImage() if isinstance(data, QPixmap) else QImage(data) buffer = QBuffer() buffer.open(QIODevice.OpenModeFlag.WriteOnly) if picture.isNull() or not picture.save(buffer, "PNG"): raise ValueError("无法读取剪贴板图片") return store_image(document, bytes(buffer.data()), label="截图") return None @dataclass class ImageRelocation: source: str files: dict[Path, bytes] def plan_image_relocation(source: str, original: Path, target: Path) -> ImageRelocation: """Read/validate every image before writing any destination resource.""" if original.resolve().parent == target.resolve().parent: return ImageRelocation(source, {}) files, edits, copied = {}, [], {} for reference in analyze_document(source).references: if not reference.image: continue parts = urlsplit(reference.url) if not parts.path or parts.scheme or parts.netloc or Path(unquote(parts.path)).is_absolute(): continue if reference.url not in copied: resource = resolve_local_reference(original, reference.url) data = resource.read_bytes() destination = target.parent / (target.stem + ".assets") / (hashlib.sha256(data).hexdigest()[:24] + resource.suffix.lower()) files[destination] = data relative = quote(destination.relative_to(target.parent).as_posix(), safe="/") copied[reference.url] = urlunsplit(("", "", relative, parts.query, parts.fragment)) edits.append(reference.edit_url(copied[reference.url])) return ImageRelocation(apply_source_edits(source, edits), files)