From 63c1216a1488b697afd06c79b0906cb1d7c989c9 Mon Sep 17 00:00:00 2001 From: harris Date: Thu, 26 Nov 2026 00:07:06 -0800 Subject: [PATCH] =?UTF-8?q?Update=20plugin=20=E5=9B=BE=E7=89=87=E6=89=B9?= =?UTF-8?q?=E5=A4=84=E7=90=86=20v0.1.4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugins/image-batch-studio/CHANGELOG.md | 12 ++ plugins/image-batch-studio/package-lock.json | 4 +- plugins/image-batch-studio/package.json | 2 +- plugins/image-batch-studio/plugin.json | 2 +- .../src/preload/compression-fallback.ts | 60 ++++++++ .../src/preload/processor.ts | 43 +++--- .../image-batch-studio/src/shared/types.ts | 2 + plugins/image-batch-studio/src/ui/App.tsx | 12 +- plugins/image-batch-studio/src/ui/styles.css | 5 + .../tests/compression-privacy.test.ts | 140 ++++++++++++++++++ 10 files changed, 253 insertions(+), 29 deletions(-) create mode 100644 plugins/image-batch-studio/src/preload/compression-fallback.ts create mode 100644 plugins/image-batch-studio/tests/compression-privacy.test.ts diff --git a/plugins/image-batch-studio/CHANGELOG.md b/plugins/image-batch-studio/CHANGELOG.md index 5b2abb4a6..70e36e71d 100644 --- a/plugins/image-batch-studio/CHANGELOG.md +++ b/plugins/image-batch-studio/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 0.1.4 - 2026-11-25 + +### Fixed + +- 修复关闭「保留元数据」时,同格式压缩结果未变小会原样导出原图、连同 EXIF/GPS/XMP/IPTC 等元数据一起保留的问题:原图带这些元数据时改为输出去元数据的重新编码结果,元数据读取失败也按含隐私信息处理。 +- 去元数据后体积比原图大时,结果列表标注「已去元数据,体积略增」,完成提示中写明数量;原图不含元数据或开启「保留元数据」时,仍保留原图以防越压越大。 + +## 0.1.3 - 2026-09-10 + +- 修复 iOS HEIC 照片触发 libheif security limits 导致解码失败与批处理中断的问题,macOS 上自动转换为兼容的临时无损图像。 +- 优化图片压缩防负优化策略:同格式纯压缩结果不小于原图时保留原图。 + ## 0.1.2 - 2026-09-01 - 适配 ZTools 3.2:截图导入、处理结果外拖,以及 Sharp runtime 使用 `pluginData` 专属目录;外拖限制为最近生成的普通文件并单次授权。 diff --git a/plugins/image-batch-studio/package-lock.json b/plugins/image-batch-studio/package-lock.json index dd9524a6f..807190287 100644 --- a/plugins/image-batch-studio/package-lock.json +++ b/plugins/image-batch-studio/package-lock.json @@ -1,12 +1,12 @@ { "name": "ztools-image-batch-studio", - "version": "0.1.2", + "version": "0.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ztools-image-batch-studio", - "version": "0.1.2", + "version": "0.1.4", "dependencies": { "gifenc": "1.0.3", "lucide-react": "1.17.0", diff --git a/plugins/image-batch-studio/package.json b/plugins/image-batch-studio/package.json index d07c313e1..7d4f7a01e 100644 --- a/plugins/image-batch-studio/package.json +++ b/plugins/image-batch-studio/package.json @@ -1,6 +1,6 @@ { "name": "ztools-image-batch-studio", - "version": "0.1.3", + "version": "0.1.4", "private": true, "type": "module", "description": "ZTools image batch processing plugin.", diff --git a/plugins/image-batch-studio/plugin.json b/plugins/image-batch-studio/plugin.json index 9e20ec47d..3610f2c36 100644 --- a/plugins/image-batch-studio/plugin.json +++ b/plugins/image-batch-studio/plugin.json @@ -4,7 +4,7 @@ "title": "图片批处理", "description": "图片批处理:压缩、水印、格式转换、尺寸、裁剪、旋转、翻转、边框、圆角、PDF 合并、图片合并和 GIF 合成。", "author": "harris", - "version": "0.1.3", + "version": "0.1.4", "main": "index.html", "preload": "preload/services.js", "logo": "logo.svg", diff --git a/plugins/image-batch-studio/src/preload/compression-fallback.ts b/plugins/image-batch-studio/src/preload/compression-fallback.ts new file mode 100644 index 000000000..a2fdcc95d --- /dev/null +++ b/plugins/image-batch-studio/src/preload/compression-fallback.ts @@ -0,0 +1,60 @@ +import type { Metadata } from "sharp"; + +/** + * 压缩结果“回退原图”的隐私判定。 + * + * 同格式纯压缩时,如果重新编码后的体积 >= 原图,旧逻辑会把原始文件原样写出, + * EXIF / GPS / XMP / IPTC 等元数据也会一起带出去,即使用户关闭了「保留元数据」。 + * 规则:去元数据优先于体积。只有原图本身不含隐私元数据, + * 或用户明确要求保留元数据时,才允许回退到原图。 + */ + +export type PrivateMetadataFields = Pick; + +export function hasPrivateMetadata(metadata: Partial): boolean { + const hasBytes = (value: Buffer | undefined) => Boolean(value && value.byteLength > 0); + return ( + hasBytes(metadata.exif) || + hasBytes(metadata.xmp) || + hasBytes(metadata.iptc) || + hasBytes(metadata.tifftagPhotoshop) || + Boolean(metadata.comments && metadata.comments.length > 0) + ); +} + +export interface CompressionFallbackInput { + /** 纯压缩、同格式、没有几何或内容变换时,才考虑回退原图。 */ + eligible: boolean; + keepMetadata: boolean; + inputBytes: number; + outputBytes: number; + /** 懒加载:只在确实要回退时才读原图元数据。读取失败一律视为含隐私元数据。 */ + sourceHasPrivateMetadata: () => Promise; +} + +export interface CompressionFallbackDecision { + useOriginal: boolean; + /** 为去掉元数据,输出比原图大,界面需要告知用户。 */ + outputLargerForPrivacy: boolean; +} + +export async function decideCompressionFallback( + input: CompressionFallbackInput +): Promise { + if (!input.eligible || input.outputBytes < input.inputBytes) { + return { useOriginal: false, outputLargerForPrivacy: false }; + } + if (input.keepMetadata) { + return { useOriginal: true, outputLargerForPrivacy: false }; + } + let carriesPrivate = true; + try { + carriesPrivate = await input.sourceHasPrivateMetadata(); + } catch { + carriesPrivate = true; + } + if (carriesPrivate) { + return { useOriginal: false, outputLargerForPrivacy: input.outputBytes > input.inputBytes }; + } + return { useOriginal: true, outputLargerForPrivacy: false }; +} diff --git a/plugins/image-batch-studio/src/preload/processor.ts b/plugins/image-batch-studio/src/preload/processor.ts index 7451f6e3c..c4f762a72 100644 --- a/plugins/image-batch-studio/src/preload/processor.ts +++ b/plugins/image-batch-studio/src/preload/processor.ts @@ -26,6 +26,7 @@ import { } from "./processing-limits"; import { sharp } from "./sharp-runtime"; import { prepareCompatibleImageInput } from "./heic-bridge"; +import { decideCompressionFallback, hasPrivateMetadata } from "./compression-fallback"; const imageExtensions = new Set(["jpg", "jpeg", "png", "webp", "avif", "heif", "heic", "tif", "tiff", "gif"]); @@ -114,15 +115,13 @@ function outputFormat(settings: ImageJobSettings, inputPath: string): ImageForma return settings.format?.type ?? formatFromPath(inputPath); } -function shouldKeepOriginalWhenCompressing( +function isCompressionFallbackEligible( settings: ImageJobSettings, inputPath: string, - format: ImageFormat, - inputBytes: number, - outputBytes: number + format: ImageFormat ): boolean { - // 当用户处于纯压缩或未修改尺寸/裁剪/水印/旋转/格式等几何或内容变换时, - // 若压缩后体积反而大于或等于原始文件体积,则保留原始文件防止“越压越大”。 + // 纯压缩、同格式、无尺寸/裁剪/水印/旋转等几何或内容变换时,才有资格回退原图防止“越压越大”; + // 是否真正回退还要经过 decideCompressionFallback 的元数据隐私判定。 const hasContentTransform = Boolean( settings.resize?.width || settings.resize?.height || @@ -138,12 +137,7 @@ function shouldKeepOriginalWhenCompressing( const inputExtFormat = formatFromPath(inputPath); const isSameFormat = format === inputExtFormat; - return Boolean( - settings.compression && - !hasContentTransform && - isSameFormat && - outputBytes >= inputBytes - ); + return Boolean(settings.compression && !hasContentTransform && isSameFormat); } function applyResize(image: Sharp, settings: ImageJobSettings, width?: number, height?: number): Sharp { @@ -440,7 +434,8 @@ async function processOne( image = await applyWatermark(image, settings); - if (settings.format?.keepMetadata || settings.compression?.keepMetadata) { + const keepMetadata = Boolean(settings.format?.keepMetadata || settings.compression?.keepMetadata); + if (keepMetadata) { image = image.withMetadata(); } @@ -448,15 +443,16 @@ async function processOne( image = applyOutputFormat(image, format, settings); const inputStat = await fs.stat(inputPath); const { data: encodedBuffer, info: outMetadata } = await image.toBuffer({ resolveWithObject: true }); - const outputBuffer = shouldKeepOriginalWhenCompressing( - settings, - inputPath, - format, - inputStat.size, - encodedBuffer.byteLength - ) - ? await fs.readFile(inputPath) - : encodedBuffer; + const fallback = await decideCompressionFallback({ + eligible: isCompressionFallbackEligible(settings, inputPath, format), + keepMetadata, + inputBytes: inputStat.size, + outputBytes: encodedBuffer.byteLength, + // 回退写出的是原始文件本身,所以必须检查原始文件(而非 HEIC 兼容中间文件)的元数据。 + sourceHasPrivateMetadata: async () => + hasPrivateMetadata(await sharp(inputPath, sharpInputOptions).metadata()) + }); + const outputBuffer = fallback.useOriginal ? await fs.readFile(inputPath) : encodedBuffer; const outputPath = buildOutputPath({ inputPath, outputDirectory: settings.output.directory, @@ -478,7 +474,8 @@ async function processOne( width: outMetadata.width, height: outMetadata.height, inputBytes: inputStat.size, - outputBytes: outputStat.size + outputBytes: outputStat.size, + ...(fallback.outputLargerForPrivacy ? { metadataStrippedLarger: true } : {}) }; } catch (error) { return { diff --git a/plugins/image-batch-studio/src/shared/types.ts b/plugins/image-batch-studio/src/shared/types.ts index cc1b5ecde..8aca54f5c 100644 --- a/plugins/image-batch-studio/src/shared/types.ts +++ b/plugins/image-batch-studio/src/shared/types.ts @@ -126,6 +126,8 @@ export interface ProcessResult { height?: number; inputBytes?: number; outputBytes?: number; + /** 关闭「保留元数据」时为去除 EXIF/GPS 等信息而重新编码,输出体积超过原图。 */ + metadataStrippedLarger?: boolean; error?: string; } diff --git a/plugins/image-batch-studio/src/ui/App.tsx b/plugins/image-batch-studio/src/ui/App.tsx index 939214410..cfa30af12 100644 --- a/plugins/image-batch-studio/src/ui/App.tsx +++ b/plugins/image-batch-studio/src/ui/App.tsx @@ -352,7 +352,12 @@ function ImageBatchWorkbench() { ); setResults(processed); const okCount = processed.filter((item) => item.ok).length; - notify(`${activeModuleLabel()}已完成 ${okCount}/${processed.length}`); + const strippedLarger = processed.filter((item) => item.ok && item.metadataStrippedLarger).length; + notify( + strippedLarger > 0 + ? `${activeModuleLabel()}已完成 ${okCount}/${processed.length},其中 ${strippedLarger} 张为移除元数据体积略增` + : `${activeModuleLabel()}已完成 ${okCount}/${processed.length}` + ); } catch (error) { showOperationError(selectedFile?.path ?? "", error); } finally { @@ -644,7 +649,10 @@ function ImageBatchWorkbench() { results.map((result) => ( )) )} diff --git a/plugins/image-batch-studio/src/ui/styles.css b/plugins/image-batch-studio/src/ui/styles.css index bd01c1c87..628c39a8a 100644 --- a/plugins/image-batch-studio/src/ui/styles.css +++ b/plugins/image-batch-studio/src/ui/styles.css @@ -650,6 +650,11 @@ input[type="color"] { text-overflow: ellipsis; } +.result-row .result-note { + font-style: normal; + color: #92400e; +} + .module-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(82px, 1fr)); diff --git a/plugins/image-batch-studio/tests/compression-privacy.test.ts b/plugins/image-batch-studio/tests/compression-privacy.test.ts new file mode 100644 index 000000000..768eb14dd --- /dev/null +++ b/plugins/image-batch-studio/tests/compression-privacy.test.ts @@ -0,0 +1,140 @@ +import { afterEach, describe, expect, it } from "vitest"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import sharp from "sharp"; +import { processImages } from "../src/preload/processor"; +import { decideCompressionFallback, hasPrivateMetadata } from "../src/preload/compression-fallback"; + +const tempDirs: string[] = []; + +async function makeTempDir() { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "ibs-privacy-")); + tempDirs.push(dir); + return dir; +} + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); +}); + +/** + * 低质量、带 EXIF + GPS 的噪点 JPEG:噪点让 q98 重编码的体积远超去掉的 EXIF 字节, + * 保证稳定命中“同格式压缩结果不小于原图”的回退分支。 + */ +async function makeJpegWithGps(filePath: string) { + const width = 96; + const height = 96; + const pixels = Buffer.alloc(width * height * 3); + let seed = 1234567; + for (let i = 0; i < pixels.length; i += 1) { + seed = (seed * 1103515245 + 12345) >>> 0; + pixels[i] = seed >>> 24; + } + await sharp(pixels, { raw: { width, height, channels: 3 } }) + .withExif({ + IFD0: { Artist: "privacy-probe", Copyright: "privacy-probe" }, + IFD3: { GPSLatitudeRef: "N", GPSLongitudeRef: "E" } + }) + .jpeg({ quality: 60, mozjpeg: true }) + .toFile(filePath); +} + +describe("decideCompressionFallback", () => { + const base = { eligible: true, keepMetadata: false, inputBytes: 100, outputBytes: 120 }; + + it("never falls back when the output is smaller", async () => { + const decision = await decideCompressionFallback({ ...base, outputBytes: 80, sourceHasPrivateMetadata: async () => true }); + expect(decision).toEqual({ useOriginal: false, outputLargerForPrivacy: false }); + }); + + it("refuses to fall back to a source that carries private metadata", async () => { + const decision = await decideCompressionFallback({ ...base, sourceHasPrivateMetadata: async () => true }); + expect(decision).toEqual({ useOriginal: false, outputLargerForPrivacy: true }); + }); + + it("treats unreadable metadata as private", async () => { + const decision = await decideCompressionFallback({ + ...base, + sourceHasPrivateMetadata: async () => { + throw new Error("boom"); + } + }); + expect(decision.useOriginal).toBe(false); + }); + + it("keeps the original when it has no private metadata", async () => { + const decision = await decideCompressionFallback({ ...base, sourceHasPrivateMetadata: async () => false }); + expect(decision).toEqual({ useOriginal: true, outputLargerForPrivacy: false }); + }); + + it("keeps the original when the user asked to keep metadata", async () => { + let probed = false; + const decision = await decideCompressionFallback({ + ...base, + keepMetadata: true, + sourceHasPrivateMetadata: async () => { + probed = true; + return true; + } + }); + expect(decision.useOriginal).toBe(true); + expect(probed).toBe(false); + }); + + it("does nothing for ineligible jobs", async () => { + const decision = await decideCompressionFallback({ ...base, eligible: false, sourceHasPrivateMetadata: async () => true }); + expect(decision).toEqual({ useOriginal: false, outputLargerForPrivacy: false }); + }); +}); + +describe("hasPrivateMetadata", () => { + it("detects exif, xmp, iptc and comments", () => { + expect(hasPrivateMetadata({})).toBe(false); + expect(hasPrivateMetadata({ exif: Buffer.alloc(0) })).toBe(false); + expect(hasPrivateMetadata({ exif: Buffer.from([1]) })).toBe(true); + expect(hasPrivateMetadata({ xmp: Buffer.from([1]) })).toBe(true); + expect(hasPrivateMetadata({ iptc: Buffer.from([1]) })).toBe(true); + expect(hasPrivateMetadata({ comments: [{ keyword: "Comment", text: "x" }] })).toBe(true); + }); +}); + +describe("processImages compression privacy", () => { + it("strips EXIF/GPS even when re-encoding makes the file larger", async () => { + const dir = await makeTempDir(); + const input = path.join(dir, "gps.jpg"); + await makeJpegWithGps(input); + expect((await sharp(input).metadata()).exif?.byteLength ?? 0).toBeGreaterThan(0); + + const [result] = await processImages([input], { + output: { directory: path.join(dir, "out"), namingPattern: "{name}-comp.{ext}", overwrite: false }, + compression: { quality: 98, keepMetadata: false } + }); + + expect(result.ok, result.error).toBe(true); + const outputBytes = await fs.readFile(result.outputPath); + const inputBytes = await fs.readFile(input); + expect(outputBytes.equals(inputBytes)).toBe(false); + const outMeta = await sharp(result.outputPath).metadata(); + expect(outMeta.exif).toBeUndefined(); + expect(outputBytes.includes(Buffer.from("privacy-probe"))).toBe(false); + // 该样本在 quality 98 下重编码必然变大:这里必须真正命中“去元数据但变大”的分支。 + expect(result.outputBytes ?? 0).toBeGreaterThan(result.inputBytes ?? 0); + expect(result.metadataStrippedLarger).toBe(true); + }); + + it("still falls back to the original when the user keeps metadata", async () => { + const dir = await makeTempDir(); + const input = path.join(dir, "gps.jpg"); + await makeJpegWithGps(input); + + const [result] = await processImages([input], { + output: { directory: path.join(dir, "out"), namingPattern: "{name}-keep.{ext}", overwrite: false }, + compression: { quality: 98, keepMetadata: true } + }); + + expect(result.ok, result.error).toBe(true); + expect(result.outputBytes).toBeLessThanOrEqual(result.inputBytes ?? 0); + expect(result.metadataStrippedLarger).toBeUndefined(); + }); +});