import fs from 'fs' import path from 'path' import { spawn, ChildProcess } from 'child_process' const IMAGE_WORKER_TIMEOUT_MS = 60_000 interface CompressionResult { uploadPath: string reason: string originalBytes: number uploadBytes: number width?: number height?: number } // 独立进程隔离 Sharp 原生库;内联脚本避免开发和打包后的路径差异。 const workerSource = ` const fs = require('fs').promises async function compress(workerData) { const sharp = require(workerData.sharpPath) sharp.concurrency(1) sharp.cache(false) const { filePath, outputPath } = workerData const source = await fs.readFile(filePath) const skipped = reason => ({ uploadPath: filePath, reason, originalBytes: source.length, uploadBytes: source.length }) const png = source.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) const jpeg = source[0] === 255 && source[1] === 216 && source[2] === 255 // 只转换静态 PNG/JPEG,其他格式保留原图,避免丢失动画帧。 if (!png && !jpeg) return skipped('不支持的格式') if (png) { for (let offset = 8; offset + 12 <= source.length;) { const length = source.readUInt32BE(offset) if (source.toString('ascii', offset + 4, offset + 8) === 'acTL') return skipped('动图') offset += length + 12 } } const image = sharp(source, { failOn: 'warning' }) const metadata = await image.metadata() if ((metadata.pages || 1) > 1) return skipped('动图') if (metadata.hasAlpha) return skipped('含透明像素') // 将 EXIF 方向固化到像素后移除元数据,不缩放图片。 const { data: buffer, info } = await image.rotate().jpeg({ quality: 90 }).toBuffer({ resolveWithObject: true }) if (!buffer.length || buffer.length > source.length * 0.9) return skipped('压缩收益不足') await fs.writeFile(outputPath, buffer) return { uploadPath: outputPath, reason: '压缩成功', originalBytes: source.length, uploadBytes: buffer.length, width: info.width, height: info.height } } process.once('message', data => { compress(data).then(result => { process.send(result, error => { if (error) process.exitCode = 1 process.disconnect() }) }).catch(error => { console.error(error.message) process.exitCode = 1 process.disconnect() }) }) ` export async function compressImage(filePath: string): Promise { const startedAt = Date.now() const outputPath = `${filePath}.upload.jpg` let worker: ChildProcess | undefined try { const { size } = await fs.promises.stat(filePath) if (size <= 2 * 1024 * 1024) { console.log('[图片处理完成] ' + JSON.stringify({ fileName: path.basename(filePath), reason: '不超过2MB', originalBytes: size, uploadBytes: size })) return filePath } worker = spawn(process.execPath, ['-e', workerSource], { env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'ignore', 'pipe', 'ipc'], windowsHide: true }) const activeWorker = worker const result = await new Promise((resolve, reject) => { let result: CompressionResult | undefined let stderr = '' let timedOut = false const timeout = setTimeout(() => { timedOut = true activeWorker.kill() }, IMAGE_WORKER_TIMEOUT_MS) activeWorker.stderr?.on('data', (chunk) => { stderr = (stderr + chunk.toString()).slice(-2000) }) activeWorker.once('message', (message: CompressionResult) => { result = message }) activeWorker.once('error', (error) => { clearTimeout(timeout) reject(error) }) // 等待真正退出后再处理文件,成功时不强杀原生库所在进程。 activeWorker.once('close', (code, signal) => { clearTimeout(timeout) if (timedOut) reject(new Error(`图片处理进程超时(${IMAGE_WORKER_TIMEOUT_MS}ms)`)) else if (code === 0 && result) resolve(result) else reject(new Error(`图片处理进程退出: code=${code}, signal=${signal}, ${stderr}`)) }) activeWorker.send({ filePath, outputPath, sharpPath: require.resolve('sharp') }, (error) => { if (error) { activeWorker.kill() // close 统一处理退出结果与清理。 stderr = error.message } }) }) const { uploadPath, ...details } = result console.log('[图片处理完成] ' + JSON.stringify({ fileName: path.basename(filePath), uploadFileName: path.basename(uploadPath), ...details, elapsedMs: Date.now() - startedAt })) return result.uploadPath } catch (error) { await fs.promises.unlink(outputPath).catch(() => undefined) console.error('[图片压缩失败] ' + JSON.stringify({ filePath, uploadPath: filePath, reason: '异常回退原图', error: (error as Error).message })) return filePath } finally { if (worker && worker.exitCode === null && worker.signalCode === null) worker.kill() } }