Repository navigation
Expand file tree
/
Copy pathimage.js
More file actions
562 lines (514 loc) · 24.6 KB
/
Copy pathimage.js
File metadata and controls
562 lines (514 loc) · 24.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
// image.js — 飞鼠格式图片转换域:图片解码/中转、图片→PDF、图片→视频、OCR 输入预处理。
// 第二批抽取自 server.js(零逻辑改动,纯搬移)。
// 注意:convertImage 的 OCR 分支延迟 require("./ocr"),避免与 ocr.js 顶层循环依赖
//(ocr.js 需要本模块的 inspectImageMetadata,本模块需要 ocr.js 的 convertImageToOcrText)。
const fs = require("fs");
const fsp = require("fs/promises");
const os = require("os");
const path = require("path");
const zlib = require("zlib");
const { finished } = require("stream/promises");
const sharp = require("sharp");
const { FFMPEG_PATH, DCRAW_PATH, CR2_DECODER_PATH, rawInput } = require("./config");
const RAW_EXTENSIONS = rawInput;
const FFMPEG_IMAGE_EXTENSIONS = new Set(["tga", "jp2", "j2k", "jxl", "qoi", "ppm"]);
const { run } = require("./utils");
const { throwIfCanceled } = require("./conversion-cancellation");
const { reportConversionProgress } = require("./conversion-progress");
const {
LIMITS,
ResourceLimitError,
assertImageMetadata,
assertImagePdfBudget
} = require("./resource-policy");
const { isBmpFileSync, decodeBmpToRaw } = require("./bmp-input");
const { isIcoFileSync, readIcoFile, extractBestFrame, decodeIcoBitmap, encodeIco } = require("./ico-format");
const { convertRasterImage, WARNING_MESSAGES } = require("./image-conversion");
// ICO 输出:把输入图缩放到多尺寸(16/24/32/48/64/128/256)生成 PNG 帧,组装成 ICO 容器。
// ICO 是静态格式;动图只取第一帧并附动画压平警告(与其它静态图片目标一致)。
async function convertToIco(inputPath, outputPath, options = {}) {
const metadata = await inspectImageMetadata(inputPath, true);
const animated = Number(metadata.pages || 1) > 1;
const warnings = [];
if (animated) warnings.push({ code: "ANIMATION_FLATTENED", messages: WARNING_MESSAGES.ANIMATION_FLATTENED });
// 尺寸自适应:只生成不超过源图尺寸的帧(避免上采样放大产生模糊),
// 但小图标档(16/24/32)必须保留——即使源图是 48px 小图,Windows 图标
// 也需要 16/32 档(2026-08-15 增强:原固定 7 档对小源图会生成模糊的 128/256 帧)。
const src = Math.max(metadata.width || 0, metadata.pageHeight || metadata.height || 0);
const sizes = [16, 24, 32, 48, 64, 128, 256]
.filter((size) => size <= src || size <= 32);
const frames = [];
for (const size of sizes) {
throwIfCanceled(options.signal);
const png = await sharp(inputPath, { page: 0, pages: 1, limitInputPixels: LIMITS.maxImagePixels })
.rotate()
.resize(size, size, { fit: "contain", withoutEnlargement: true, background: { r: 0, g: 0, b: 0, alpha: 0 } })
.toColorspace("srgb")
.ensureAlpha()
.png()
.toBuffer();
frames.push({ size, data: png });
}
throwIfCanceled(options.signal);
await fsp.writeFile(outputPath, encodeIco(frames));
return { warnings };
}
async function convertImage(inputPath, outputPath, target, options = {}) {
throwIfCanceled(options.signal);
const prepared = await prepareImageInput(inputPath, options.inputName);
try {
throwIfCanceled(options.signal);
if (target === "pdf") {
await convertImagesToPdf([{ inputPath: prepared.inputPath, originalName: path.basename(prepared.inputPath) }], outputPath, options);
return { warnings: [] };
}
if (target === "txt") {
const { convertImageToOcrText } = require("./ocr");
return await convertImageToOcrText(prepared.inputPath, outputPath, options);
}
if (target === "docx" || target === "md") {
const { recognizeImageResult } = require("./ocr");
const result = await recognizeImageResult(prepared.inputPath, options);
if (!result.text.trim()) {
const error = new Error("OCR 没有识别出文字,请确认图片清晰、方向正确。");
error.code = "OCR_NO_TEXT";
error.messages = { zhCN: error.message, enUS: "OCR found no text. Check image clarity and orientation." };
throw error;
}
if (target === "docx") {
await require("./text-docx").convertTextToDocx(result.text, "txt", outputPath);
} else {
const text = result.text.replace(/([\\`*_\[\]<>|#])/g, '\\$1');
await fsp.writeFile(outputPath, text + '\n', "utf8");
}
return { warnings: [...result.warnings, { code: "OCR_EDITABLE_TEXT", messages: {
zhCN: "已生成可编辑文字;原图中的表格、图片位置和样式未重建,请对照原图复核。",
enUS: "Editable text was created. Original tables, image positions and styling were not reconstructed; review against the source image."
} }] };
}
if (target === "ico") {
return await convertToIco(prepared.inputPath, outputPath, options);
}
// 专业/新式位图输出:sharp 的预编译编码器不全,统一走打包内置 ffmpeg。
// jxl 显式指定 libjxl,其余按扩展名选 muxer;五种格式均已做编码→解码闭环实测。
if (FFMPEG_IMAGE_EXTENSIONS.has(target)) {
const args = ["-hide_banner", "-y", "-i", prepared.inputPath, "-frames:v", "1"];
if (target === "jxl") args.push("-c:v", "libjxl");
args.push(outputPath);
await run(FFMPEG_PATH, args, { timeout: 1000 * 60 * 5 });
return { warnings: [] };
}
if (target === "mp4" || target === "webm") {
await convertImageToVideo(prepared.inputPath, outputPath, target);
return { warnings: [] };
}
await inspectImageMetadata(prepared.inputPath, true);
// 必须 await:finally 会删除 BMP 解码的临时目录,未 await 时删除先于转换完成,
// macOS(文件可删)会报 decoded.png missing,Windows(句柄占用删除失败)侥幸通过。
const result = await convertRasterImage(prepared.inputPath, outputPath, target, { maxPixels: LIMITS.maxImagePixels });
return result;
} finally {
if (prepared.tempDir) await fsp.rm(prepared.tempDir, { recursive: true, force: true }).catch(() => {});
}
}
// sharp 的预编译构建不支持 BMP 输入(无解码器)且 libheif 只编译了 AV1(AVIF),
// HEIC/HEIF(HEVC 编码)能读元数据但解不了像素。这里统一中转:
// - BMP -> 纯 JS 解码成 PNG
// - HEIC -> 打包内置 ffmpeg(含 hevc 解码器)转 PNG
// 让下游统一走 PNG。
async function prepareImageInput(inputPath, inputName) {
// 设计稿(.ai/.psd):先统一栅格化成 PNG 再走通用图片链路。
// multer 临时文件无扩展名,按上传原始名(inputName)识别;多页 .ai 只取第 1 页
// (包装稿典型为单页;实验性输入已附提示复核产物)。
const designExt = path.extname(String(inputName || inputPath)).toLowerCase().replace(/^\./, "");
if (designExt === "ai" || designExt === "psd") {
const { designToPng } = require("./design-export");
return await designToPng(inputPath, designExt);
}
// 先读文件头判断(不整读大图);只有需要中转的格式才解码进内存。
if (isIcoFileSync(inputPath)) {
// ICO 容器:提取最清晰帧(PNG 帧直接落盘;BMP DIB 帧解码成 raw 再转 PNG)。
const frame = extractBestFrame(await readIcoFile(inputPath));
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-ico-input-"));
const pngPath = path.join(tempDir, "decoded.png");
try {
if (frame.png) {
await fsp.writeFile(pngPath, frame.data);
} else {
const { width, height, channels, data } = decodeIcoBitmap(frame);
await sharp(data, { raw: { width, height, channels }, limitInputPixels: LIMITS.maxImagePixels })
.png()
.toFile(pngPath);
}
return { inputPath: pngPath, tempDir };
} catch (error) {
await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
throw error;
}
}
if (isBmpFileSync(inputPath)) {
const { width, height, channels, data } = decodeBmpToRaw(await fsp.readFile(inputPath));
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-bmp-input-"));
const pngPath = path.join(tempDir, "decoded.png");
await sharp(data, { raw: { width, height, channels }, limitInputPixels: LIMITS.maxImagePixels })
.png()
.toFile(pngPath);
return { inputPath: pngPath, tempDir };
}
if (isHeicFileSync(inputPath)) {
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-heic-input-"));
const pngPath = path.join(tempDir, "decoded.png");
await run(FFMPEG_PATH, ["-hide_banner", "-y", "-i", inputPath, pngPath], { timeout: 1000 * 60 * 5 });
if (!fs.existsSync(pngPath)) {
await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
throw new Error("HEIC 图片解码失败:无法从该文件提取像素数据。");
}
return { inputPath: pngPath, tempDir };
}
// 专业/新式位图输入在 Electron 上传后临时路径没有扩展名;这类容器的探测并非都
// 稳定,先按 inputName 补回扩展名,再用 ffmpeg 解码成 PNG 供下游统一处理。
if (FFMPEG_IMAGE_EXTENSIONS.has(designExt) || isTgaFileSync(inputPath)) {
const sourceExt = FFMPEG_IMAGE_EXTENSIONS.has(designExt) ? designExt : "tga";
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-ffmpeg-image-input-"));
const namedInput = path.join(tempDir, `input.${sourceExt}`);
const pngPath = path.join(tempDir, "decoded.png");
await fsp.copyFile(inputPath, namedInput);
await run(FFMPEG_PATH, ["-hide_banner", "-y", "-i", namedInput, "-frames:v", "1", pngPath], { timeout: 1000 * 60 * 5 });
if (!fs.existsSync(pngPath)) {
await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
throw new Error(`${sourceExt.toUpperCase()} 图片解码失败:无法从该文件提取像素数据。`);
}
return { inputPath: pngPath, tempDir };
}
// 相机 RAW 原片(CR2/NEF/ARW/DNG 等):sharp/libvips 无 dcraw delegate,用打包内置
// dcraw.exe 按相机白平衡解出 sRGB TIFF,让下游统一走 sharp。
if (RAW_EXTENSIONS.has(designExt) || isRawFileSync(inputPath)) {
const rawExt = designExt || path.extname(inputPath).slice(1).toLowerCase();
const useLibRaw = rawExt === "cr2" && Boolean(CR2_DECODER_PATH);
const decoder = useLibRaw ? CR2_DECODER_PATH : DCRAW_PATH;
if (!decoder) {
throw new Error("RAW 解码引擎(dcraw)不可用:未找到 dcraw.exe。");
}
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-raw-input-"));
// dcraw 不支持 -O(部分版本报 Unknown option),输出 <basename>.tiff 固定生成在输入
// 所在目录。先把输入复制到临时目录再解码:源目录可能只读(U 盘/系统目录),
// 且避免在用户目录残留 .tiff。
const tempInput = path.join(tempDir, `input.${designExt || path.extname(inputPath).replace(/^\./, "") || "raw"}`);
try {
await fsp.copyFile(inputPath, tempInput);
// -T selects TIFF (8-bit by default); -o 1 selects sRGB.
// Without -w dcraw uses fixed daylight WB, ignoring the camera setting.
// Preserve intentional warm lighting; do not auto-neutralize every photo.
const args = ["-T", "-o", "1", "-w"];
// LibRaw defaults to input.cr2.tiff; use its explicit output option.
// CR2 uses maintained LibRaw because legacy dcraw crashes on e.g. EOS M100.
if (useLibRaw) args.push("-Z", path.join(tempDir, "input.tiff"));
args.push(tempInput);
await run(decoder, args, { timeout: 1000 * 60 * 5 });
const stem = path.basename(tempInput, path.extname(tempInput));
const tiffCandidates = [
path.join(tempDir, `${stem}.tiff`),
path.join(tempDir, `${stem}.tif`)
];
const tiffPath = tiffCandidates.find((c) => fs.existsSync(c));
if (!tiffPath) throw new Error("RAW 图片解码失败:无法从该文件提取像素数据。");
return { inputPath: tiffPath, tempDir };
} catch (error) {
// prepareImageInput can fail before convertImage's finally is entered.
// Preserve the decoder's original error while removing this attempt only.
await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
throw error;
}
}
return { inputPath, tempDir: null };
}
// 相机 RAW 扩展名白名单(与 config.rawInput 对应;按扩展名判断,不读文件头——
// RAW 无统一魔数,dcraw 靠内容识别,这里先按扩展名分流)
function isRawFileSync(filePath) {
const ext = path.extname(filePath).toLowerCase().replace(/^\./, "");
return RAW_EXTENSIONS.has(ext);
}
// HEIC/HEIF 是 ISO BMFF 容器(ftyp 盒子),major brand 为 heic/heif/mif1/heix/heim;
// AVIF(avif/avis)sharp 原生可解,不在此中转范围。
function isHeicFileSync(filePath) {
const fd = fs.openSync(filePath, "r");
try {
const header = Buffer.alloc(12);
const read = fs.readSync(fd, header, 0, 12, 0);
if (read < 12) return false;
const boxType = header.toString("latin1", 4, 8);
const majorBrand = header.toString("latin1", 8, 12).toLowerCase();
return boxType === "ftyp" && ["heic", "heif", "mif1", "heix", "heim"].includes(majorBrand);
} catch {
return false;
} finally {
fs.closeSync(fd);
}
}
// TGA(Truevision Targa)是简单位图容器:18 字节头(imageType 字段)+ 可选调色板 +
// 像素数据(未压缩或 RLE)。sharp/libvips 无 TGA 解码器,但内置 ffmpeg 支持,按扩展名
// 分流(与 RAW 同理,TGA 无统一魔数)。旧版 TGA 尾部可能带 "TRUEVISION-XFILE." 签名,
// 但很多软件不写,不能作为可靠判据。
function isTgaFileSync(filePath) {
const ext = path.extname(filePath).toLowerCase().replace(/^\./, "");
return ext === "tga";
}
async function inspectImageMetadata(inputPath, animated = false) {
if (isIcoFileSync(inputPath)) {
const frame = extractBestFrame(await readIcoFile(inputPath));
const metadata = frame.png
? await sharp(frame.data, { limitInputPixels: LIMITS.maxImagePixels }).metadata()
: { width: frame.width, height: frame.height, pages: 1, hasAlpha: true };
assertImageMetadata(metadata);
return metadata;
}
let metadata;
try {
metadata = await sharp(inputPath, {
animated,
limitInputPixels: LIMITS.maxImagePixels
}).metadata();
} catch (error) {
if (/pixel limit|input image exceeds/i.test(String(error?.message || ""))) {
throw new ResourceLimitError("IMAGE_PIXELS_EXCEEDED");
}
throw error;
}
assertImageMetadata(metadata);
return metadata;
}
async function convertImageToVideo(inputPath, outputPath, target) {
const fd = fs.openSync(inputPath, "r");
let isGif = false;
try {
const magic = Buffer.alloc(6);
fs.readSync(fd, magic, 0, 6, 0);
isGif = magic.toString("latin1") === "GIF87a" || magic.toString("latin1") === "GIF89a";
} finally {
fs.closeSync(fd);
}
const args = ["-hide_banner", "-y"];
if (isGif) {
args.push("-i", inputPath);
} else {
args.push("-loop", "1", "-i", inputPath, "-t", "3");
}
args.push("-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2", "-an");
if (target === "mp4") {
args.push("-codec:v", "libx264", "-preset", "medium", "-crf", "23", "-pix_fmt", "yuv420p", "-movflags", "+faststart");
} else {
args.push("-codec:v", "libvpx-vp9", "-crf", "30", "-b:v", "0", "-pix_fmt", "yuv420p");
}
args.push(outputPath);
await run(FFMPEG_PATH, args, { timeout: 1000 * 60 * 10 });
}
function pdfAscii(value) {
return Buffer.from(value, "latin1");
}
function pdfNumber(value) {
return Number(value).toFixed(2).replace(/\.00$/, "");
}
async function readImageForPdf(inputPath, options = {}) {
throwIfCanceled(options.signal);
if (isIcoFileSync(inputPath)) {
const prepared = await prepareImageInput(inputPath);
try {
throwIfCanceled(options.signal);
return await readPngAsPdfImage(prepared.inputPath);
} finally {
await fsp.rm(prepared.tempDir, { recursive: true, force: true }).catch(() => {});
}
}
// sharp 的预编译构建不支持 BMP 输入:批量/ZIP 图片合并 PDF 时直接解码 BMP。
// 先读文件头判断,避免把非 BMP 大图整读进内存。
if (isBmpFileSync(inputPath)) {
const rawBmp = decodeBmpToRaw(fs.readFileSync(inputPath));
let data = rawBmp.data;
// PDF 位图流按 RGB 三通道写入:带 alpha 的 32bpp BMP(decodeBmpToRaw 输出 4 通道)
// 必须先剥掉 alpha 拍平为 RGB,否则每行多一字节导致整图错位。
if (rawBmp.channels === 4) {
const rgb = Buffer.alloc(rawBmp.width * rawBmp.height * 3);
for (let i = 0, j = 0; i < data.length; i += 4, j += 3) {
rgb[j] = data[i]; rgb[j + 1] = data[i + 1]; rgb[j + 2] = data[i + 2];
}
data = rgb;
}
return {
width: rawBmp.width,
height: rawBmp.height,
data: zlib.deflateSync(data)
};
}
// HEIC/HEIF(HEVC)sharp 解不了像素,用 ffmpeg 转 PNG 再提取 raw。
if (isHeicFileSync(inputPath)) {
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-heic-pdf-"));
try {
const pngPath = path.join(tempDir, "decoded.png");
await run(FFMPEG_PATH, ["-hide_banner", "-y", "-i", inputPath, pngPath], { timeout: 1000 * 60 * 5, signal: options.signal });
throwIfCanceled(options.signal);
return await readPngAsPdfImage(pngPath);
} finally {
await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
}
}
// TGA 同理:sharp 无解码器,用 ffmpeg 转 PNG 再提取 raw(图片合并 PDF 路径)。
if (isTgaFileSync(inputPath)) {
const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), "flyingmouse-tga-pdf-"));
try {
const pngPath = path.join(tempDir, "decoded.png");
await run(FFMPEG_PATH, ["-hide_banner", "-y", "-i", inputPath, "-frames:v", "1", pngPath], { timeout: 1000 * 60 * 5, signal: options.signal });
throwIfCanceled(options.signal);
return await readPngAsPdfImage(pngPath);
} finally {
await fsp.rm(tempDir, { recursive: true, force: true }).catch(() => {});
}
}
return readPngAsPdfImage(inputPath);
}
async function readPngAsPdfImage(inputPath) {
const { data, info } = await sharp(inputPath, { limitInputPixels: LIMITS.maxImagePixels })
.rotate()
.flatten({ background: "#ffffff" })
.toColorspace("srgb")
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const channels = info.channels || 3;
let rgb = data;
if (channels !== 3) {
rgb = Buffer.alloc(info.width * info.height * 3);
for (let pixel = 0; pixel < info.width * info.height; pixel += 1) {
rgb[pixel * 3] = data[pixel * channels];
rgb[pixel * 3 + 1] = data[pixel * channels + 1];
rgb[pixel * 3 + 2] = data[pixel * channels + 2];
}
}
return {
width: info.width,
height: info.height,
data: zlib.deflateSync(rgb)
};
}
// 流式写入辅助:向 PDF 输出流逐块写入,并同步累计字节位置(供 xref 偏移使用)。
// 每块等待实际写入完成,既限制写缓冲,也把打开/写盘失败交回转换请求。
function writePdfChunk(stream, buffer, pos) {
pos.value += buffer.length;
return new Promise((resolve, reject) => {
stream.write(buffer, (error) => error ? reject(error) : resolve());
});
}
// 图片合并为 PDF:逐张解码、流式写盘并释放整图数据,元数据与页目录仍按页数增长。
// 先检查设备预算;每张图以原始分辨率整页内嵌,不为满足预算而缩放。
async function convertImagesToPdf(imageFiles, outputPath, options = {}) {
const { signal, onProgress = () => {} } = options;
throwIfCanceled(signal);
if (!imageFiles.length) {
throw new Error("请先选择要转换为 PDF 的图片。");
}
// Validate dimensions and the finite device budget before decoding pixels or
// writing pages, so invalid/oversized input cannot produce partial success.
reportConversionProgress({ stage: "preparing" });
const metadataList = [];
for (const file of imageFiles) {
throwIfCanceled(signal);
if (file?.blank) {
metadataList.push({ width: 595, height: 842, pages: 1, pageHeight: 842 });
continue;
}
metadataList.push(await inspectImageMetadata(file.inputPath));
}
throwIfCanceled(signal);
assertImagePdfBudget(metadataList);
// 页对象编号是确定的(3 + index*3),可先算好 Kids 列表,再写 /Pages 对象 2。
const count = imageFiles.length;
reportConversionProgress({ stage: "merging", completed: 0, total: count, unit: "pages" });
const pageRefs = [];
for (let index = 0; index < count; index += 1) {
pageRefs.push(`${3 + index * 3} 0 R`);
}
const stream = fs.createWriteStream(outputPath);
// Keep the error listener alive even while decoding the next image. Otherwise
// an asynchronous open/write error can terminate the whole desktop process.
const completion = finished(stream);
completion.catch(() => {});
const pos = { value: 0 };
const offsets = {};
try {
// PDF 头必须在最前(对象偏移从头部之后起算)
await writePdfChunk(stream, pdfAscii("%PDF-1.4\n"), pos);
offsets[1] = pos.value;
await writePdfChunk(stream, pdfAscii("1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"), pos);
offsets[2] = pos.value;
await writePdfChunk(stream, pdfAscii(`2 0 obj\n<< /Type /Pages /Kids [${pageRefs.join(" ")}] /Count ${pageRefs.length} >>\nendobj\n`), pos);
for (let index = 0; index < count; index += 1) {
throwIfCanceled(signal);
const file = imageFiles[index];
const pageNumber = 3 + index * 3;
const imageNumber = pageNumber + 1;
const contentNumber = pageNumber + 2;
let image;
if (file?.blank) {
// 空白页:A4 竖版比例(595×842pt),纯白 RGB 图像,deflate 压缩
const blankWidth = 595;
const blankHeight = 842;
image = {
width: blankWidth,
height: blankHeight,
data: zlib.deflateSync(Buffer.alloc(blankWidth * blankHeight * 3, 0xff))
};
} else {
image = await readImageForPdf(file.inputPath, options);
}
throwIfCanceled(signal);
const pageWidth = Math.max(1, image.width);
const pageHeight = Math.max(1, image.height);
// Page 对象
offsets[pageNumber] = pos.value;
await writePdfChunk(stream, pdfAscii(`${pageNumber} 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${pdfNumber(pageWidth)} ${pdfNumber(pageHeight)}] /Resources << /XObject << /Im${index + 1} ${imageNumber} 0 R >> >> /Contents ${contentNumber} 0 R >>\nendobj\n`), pos);
// Image(XObject) 对象:头 + 压缩流 + 尾部,分三段写,避免为当前图额外拼一份拷贝
offsets[imageNumber] = pos.value;
await writePdfChunk(stream, pdfAscii(`${imageNumber} 0 obj\n<< /Type /XObject /Subtype /Image /Width ${image.width} /Height ${image.height} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode /Length ${image.data.length} >>\nstream\n`), pos);
await writePdfChunk(stream, image.data, pos);
await writePdfChunk(stream, pdfAscii("\nendstream\nendobj\n"), pos);
// 本页图数据已写盘,置空以尽早释放(不随张数累积)
image = null;
// Contents 对象
offsets[contentNumber] = pos.value;
const content = `q\n${pdfNumber(pageWidth)} 0 0 ${pdfNumber(pageHeight)} 0 0 cm\n/Im${index + 1} Do\nQ\n`;
await writePdfChunk(stream, pdfAscii(`${contentNumber} 0 obj\n<< /Length ${Buffer.byteLength(content, "latin1")} >>\nstream\n${content}endstream\nendobj\n`), pos);
reportConversionProgress({ stage: "merging", completed: index + 1, total: count, unit: "pages" });
onProgress({ stage: "merging", completedPages: index + 1, totalPages: count, percent: (index + 1) / count * 100 });
throwIfCanceled(signal);
}
throwIfCanceled(signal);
const xrefOffset = pos.value;
const objectCount = Object.keys(offsets).length;
let xref = `xref\n0 ${objectCount + 1}\n0000000000 65535 f \n`;
for (let number = 1; number <= objectCount; number += 1) {
xref += `${String(offsets[number]).padStart(10, "0")} 00000 n \n`;
}
const trailer = `trailer\n<< /Size ${objectCount + 1} /Root 1 0 R >>\nstartxref\n${xrefOffset}\n%%EOF\n`;
await writePdfChunk(stream, pdfAscii(xref + trailer), pos);
stream.end();
await completion;
reportConversionProgress({ stage: "validating" });
} catch (error) {
stream.destroy();
await completion.catch(() => {});
throw error;
}
}
module.exports = {
convertImage,
prepareImageInput,
isHeicFileSync,
isTgaFileSync,
isRawFileSync,
inspectImageMetadata,
convertImageToVideo,
pdfAscii,
pdfNumber,
readImageForPdf,
readPngAsPdfImage,
convertImagesToPdf
};