Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions plugins/image-batch-studio/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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` 专属目录;外拖限制为最近生成的普通文件并单次授权。
Expand Down
4 changes: 2 additions & 2 deletions plugins/image-batch-studio/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion plugins/image-batch-studio/package.json
Original file line number Diff line number Diff line change
@@ -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.",
Expand Down
2 changes: 1 addition & 1 deletion plugins/image-batch-studio/plugin.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
60 changes: 60 additions & 0 deletions plugins/image-batch-studio/src/preload/compression-fallback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import type { Metadata } from "sharp";

/**
* 压缩结果“回退原图”的隐私判定。
*
* 同格式纯压缩时,如果重新编码后的体积 >= 原图,旧逻辑会把原始文件原样写出,
* EXIF / GPS / XMP / IPTC 等元数据也会一起带出去,即使用户关闭了「保留元数据」。
* 规则:去元数据优先于体积。只有原图本身不含隐私元数据,
* 或用户明确要求保留元数据时,才允许回退到原图。
*/

export type PrivateMetadataFields = Pick<Metadata, "exif" | "xmp" | "iptc" | "tifftagPhotoshop" | "comments">;

export function hasPrivateMetadata(metadata: Partial<PrivateMetadataFields>): 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<boolean>;
}

export interface CompressionFallbackDecision {
useOriginal: boolean;
/** 为去掉元数据,输出比原图大,界面需要告知用户。 */
outputLargerForPrivacy: boolean;
}

export async function decideCompressionFallback(
input: CompressionFallbackInput
): Promise<CompressionFallbackDecision> {
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 };
}
43 changes: 20 additions & 23 deletions plugins/image-batch-studio/src/preload/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);

Expand Down Expand Up @@ -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 ||
Expand All @@ -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 {
Expand Down Expand Up @@ -440,23 +434,25 @@ 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();
}

const format = outputFormat(settings, inputPath);
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,
Expand All @@ -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 {
Expand Down
2 changes: 2 additions & 0 deletions plugins/image-batch-studio/src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ export interface ProcessResult {
height?: number;
inputBytes?: number;
outputBytes?: number;
/** 关闭「保留元数据」时为去除 EXIF/GPS 等信息而重新编码,输出体积超过原图。 */
metadataStrippedLarger?: boolean;
error?: string;
}

Expand Down
12 changes: 10 additions & 2 deletions plugins/image-batch-studio/src/ui/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -644,7 +649,10 @@ function ImageBatchWorkbench() {
results.map((result) => (
<button key={`${result.inputPath}-${result.outputPath}`} className="result-row" draggable={Boolean(result.outputPath && window.services.canStartDrag())} onDragStart={(event) => result.outputPath && void dragResult(event, result.outputPath)} onClick={() => result.outputPath && window.services.reveal(result.outputPath)}>
{result.ok ? <Check size={14} /> : <PanelRight size={14} />}
<span>{result.ok ? basename(result.outputPath) : result.error}</span>
<span title={result.metadataStrippedLarger ? "已移除 EXIF/GPS 等元数据,输出比原图略大" : undefined}>
{result.ok ? basename(result.outputPath) : result.error}
{result.metadataStrippedLarger && <em className="result-note"> · 已去元数据,体积略增</em>}
</span>
</button>
))
)}
Expand Down
5 changes: 5 additions & 0 deletions plugins/image-batch-studio/src/ui/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
140 changes: 140 additions & 0 deletions plugins/image-batch-studio/tests/compression-privacy.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
});
Loading