Files
Clipboard/lib/image-cap.js
2026-09-12 13:59:12 +08:00

39 lines
1.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
const { nativeImage } = require('electron');
const PREVIEW_BYTES = 12 * 1024; // >12 KB → needs resizing for inline preview
const SOFT_CAP_BYTES = 2 * 1024 * 1024; // 2 MB
const RESIZE_WIDTH = 800; // 大图压到这个宽度,保证 SOFT_CAP_BYTES 不爆
/**
* Returns { buf, preview }.
* - buf: input buffer unchanged.
* - preview: null if the buffer is < PREVIEW_BYTES (12 KB), otherwise the
* literal string '[图片]'. The caller (main.js) is responsible for
* actually resizing when buf.length > SOFT_CAP_BYTES (2 MB); the
* preview marker is purely a signal that the buffer is non-trivial.
*/
function capImage(buf) {
const b = Buffer.isBuffer(buf) ? buf : Buffer.from(buf || []);
if (b.length < PREVIEW_BYTES) return { buf: b, preview: null };
return { buf: b, preview: '[图片]' };
}
/**
* 把图片 buffer 按 SOFT_CAP_BYTES 收纳:超出的图压成 RESIZE_WIDTH 宽。
* 三处共用pollClipboard / bringFavoriteIntoHistory。
*
* 返回 { buf, preview }preview 由 capImage 给出(无图/小图 = null
* 给数据库的 preview 列用。
*/
function normalizeImageForStorage(buf) {
const cap = capImage(buf);
// 小图/空图:直接原样入库
if (!cap.preview) return cap;
if (cap.buf.length <= SOFT_CAP_BYTES) return cap;
// 大图nativeImage 重新编码到 RESIZE_WIDTH 宽PNG 重编码比原图小一个数量级
const img = nativeImage.createFromBuffer(cap.buf);
return { buf: img.resize({ width: RESIZE_WIDTH }).toPNG(), preview: cap.preview };
}
module.exports = { capImage, normalizeImageForStorage, PREVIEW_BYTES, SOFT_CAP_BYTES, RESIZE_WIDTH };