/** * 零依赖 PNG 解码 / 编码 / 透明通道提取 * 背景:macOS qlmanage 渲染 SVG 时会合成到不透明白底上,无法直接得到透明 PNG。 * 方案:同一张 SVG 分别渲染到「白底」「黑底」两次,用两式联立解出真实的 alpha 与颜色: * Pw = a·C + (1-a)·255 * Pb = a·C + (1-a)·0 * => a = 1 - (Pw - Pb)/255, C = Pb / a * 结果就是精确抗锯齿的真实透明 PNG。 */ import zlib from 'node:zlib' const SIG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) let CRC_TABLE = null function crcTable() { if (CRC_TABLE) return CRC_TABLE CRC_TABLE = new Int32Array(256) for (let n = 0; n < 256; n++) { let c = n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1 CRC_TABLE[n] = c } return CRC_TABLE } function crc32(buf) { const t = crcTable() let c = 0xffffffff for (let i = 0; i < buf.length; i++) c = t[(c ^ buf[i]) & 0xff] ^ (c >>> 8) return (c ^ 0xffffffff) >>> 0 } function chunk(type, data) { const len = Buffer.alloc(4) len.writeUInt32BE(data.length, 0) const typeBuf = Buffer.from(type, 'ascii') const crc = Buffer.alloc(4) crc.writeUInt32BE(crc32(Buffer.concat([typeBuf, data])), 0) return Buffer.concat([len, typeBuf, data, crc]) } /** 解码 PNG -> { width, height, rgba: Buffer(RGBA) } */ export function decodePng(buf) { if (!buf.slice(0, 8).equals(SIG)) throw new Error('不是有效的 PNG') let off = 8 let width = 0 let height = 0 let colorType = 0 let bitDepth = 0 const idat = [] while (off < buf.length) { const len = buf.readUInt32BE(off) const type = buf.toString('ascii', off + 4, off + 8) const data = buf.slice(off + 8, off + 8 + len) if (type === 'IHDR') { width = data.readUInt32BE(0) height = data.readUInt32BE(4) bitDepth = data[8] colorType = data[9] } else if (type === 'IDAT') idat.push(data) else if (type === 'IEND') break off += 12 + len } if (bitDepth !== 8) throw new Error('仅支持 8bit PNG') const ch = colorType === 6 ? 4 : colorType === 2 ? 3 : colorType === 4 ? 2 : 1 const raw = zlib.inflateSync(Buffer.concat(idat)) const stride = width * ch const rgba = Buffer.alloc(width * height * 4) let prev = Buffer.alloc(stride) for (let y = 0; y < height; y++) { const ft = raw[y * (stride + 1)] const line = Buffer.from(raw.slice(y * (stride + 1) + 1, y * (stride + 1) + 1 + stride)) for (let i = 0; i < stride; i++) { const a = i >= ch ? line[i - ch] : 0 const b = prev[i] const c = i >= ch ? prev[i - ch] : 0 if (ft === 1) line[i] = (line[i] + a) & 255 else if (ft === 2) line[i] = (line[i] + b) & 255 else if (ft === 3) line[i] = (line[i] + ((a + b) >> 1)) & 255 else if (ft === 4) { const p = a + b - c const pa = Math.abs(p - a) const pb = Math.abs(p - b) const pc = Math.abs(p - c) line[i] = (line[i] + (pa <= pb && pa <= pc ? a : pb <= pc ? b : c)) & 255 } } for (let x = 0; x < width; x++) { const si = x * ch const di = (y * width + x) * 4 if (ch === 4) { rgba[di] = line[si]; rgba[di + 1] = line[si + 1]; rgba[di + 2] = line[si + 2]; rgba[di + 3] = line[si + 3] } else if (ch === 3) { rgba[di] = line[si]; rgba[di + 1] = line[si + 1]; rgba[di + 2] = line[si + 2]; rgba[di + 3] = 255 } else { rgba[di] = rgba[di + 1] = rgba[di + 2] = line[si]; rgba[di + 3] = ch === 2 ? line[si + 1] : 255 } } prev = line } return { width, height, rgba } } /** * 编码 RGBA -> PNG(无损) * filter:PNG 行滤波器,0=不过滤(默认,保持图标产物字节不变)、1=Sub、2=Up、3=Avg、4=Paeth。 * 大面积渐变图(如轮播配图)用 1~4 可把体积降到 1/3 以下;图形类图标用 0 已足够小。 */ export function encodePng({ width, height, rgba }, { filter = 0 } = {}) { const stride = width * 4 const raw = Buffer.alloc((stride + 1) * height) const bpp = 4 if (!filter) { for (let y = 0; y < height; y++) { raw[y * (stride + 1)] = 0 rgba.copy(raw, y * (stride + 1) + 1, y * stride, y * stride + stride) } } else { let prev = Buffer.alloc(stride) const line = Buffer.alloc(stride) for (let y = 0; y < height; y++) { const base = y * stride for (let i = 0; i < stride; i++) { const cur = rgba[base + i] const a = i >= bpp ? rgba[base + i - bpp] : 0 const b = prev[i] const c = i >= bpp ? prev[i - bpp] : 0 let pred if (filter === 1) pred = a else if (filter === 2) pred = b else if (filter === 3) pred = (a + b) >> 1 else { const p = a + b - c const pa = Math.abs(p - a) const pb = Math.abs(p - b) const pc = Math.abs(p - c) pred = pa <= pb && pa <= pc ? a : pb <= pc ? b : c } line[i] = (cur - pred) & 255 } raw[y * (stride + 1)] = filter line.copy(raw, y * (stride + 1) + 1) prev = Buffer.from(line) } } const ihdr = Buffer.alloc(13) ihdr.writeUInt32BE(width, 0) ihdr.writeUInt32BE(height, 4) ihdr[8] = 8 ihdr[9] = 6 return Buffer.concat([SIG, chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw, { level: 9 })), chunk('IEND', Buffer.alloc(0))]) } /** 由「白底」「黑底」两张同尺寸渲染图解出真实透明 RGBA */ export function extractAlpha(white, black) { const { width, height } = white const out = Buffer.alloc(width * height * 4) for (let i = 0; i < width * height; i++) { const di = i * 4 const dw = ((white.rgba[di] - black.rgba[di]) + (white.rgba[di + 1] - black.rgba[di + 1]) + (white.rgba[di + 2] - black.rgba[di + 2])) / 3 let a = 1 - dw / 255 if (a < 0) a = 0 if (a > 1) a = 1 if (a <= 0.008) { out[di] = 0; out[di + 1] = 0; out[di + 2] = 0; out[di + 3] = 0 continue } out[di] = Math.min(255, Math.round(black.rgba[di] / a)) out[di + 1] = Math.min(255, Math.round(black.rgba[di + 1] / a)) out[di + 2] = Math.min(255, Math.round(black.rgba[di + 2] / a)) out[di + 3] = Math.round(a * 255) } return { width, height, rgba: out } } /** 统计透明像素占比(用于自检) */ export function transparentRatio(img) { let n = 0 for (let i = 0; i < img.width * img.height; i++) if (img.rgba[i * 4 + 3] < 10) n++ return n / (img.width * img.height) } /** * 求「非纯白像素」的包围盒。 * 用途:qlmanage 会把 SVG 渲染到一个更小的子矩形里,其余填充纯白衬底, * 因此对「黑底渲染图」求非白包围盒即可精确定位真实内容区域。 */ export function contentBox(img) { const { width: W, height: H, rgba } = img let minX = W let maxX = -1 let minY = H let maxY = -1 for (let y = 0; y < H; y++) { for (let x = 0; x < W; x++) { const d = (y * W + x) * 4 const isWhite = rgba[d] >= 250 && rgba[d + 1] >= 250 && rgba[d + 2] >= 250 if (!isWhite) { if (x < minX) minX = x if (x > maxX) maxX = x if (y < minY) minY = y if (y > maxY) maxY = y } } } if (maxX < 0) return { x: 0, y: 0, w: W, h: H } return { x: minX, y: minY, w: maxX - minX + 1, h: maxY - minY + 1 } } /** 按包围盒裁剪 */ export function crop(img, box) { const out = Buffer.alloc(box.w * box.h * 4) for (let y = 0; y < box.h; y++) { const src = ((box.y + y) * img.width + box.x) * 4 img.rgba.copy(out, y * box.w * 4, src, src + box.w * 4) } return { width: box.w, height: box.h, rgba: out } } /** * 整数倍降采样(盒式滤波,按预乘 alpha 平均,避免半透明边缘发暗) * 用于把高分辨率渲染结果压到目标尺寸,兼顾锐度与体积。 */ export function downscale(img, factor) { if (factor <= 1) return img const w = Math.floor(img.width / factor) const h = Math.floor(img.height / factor) const out = Buffer.alloc(w * h * 4) const n = factor * factor for (let y = 0; y < h; y++) { for (let x = 0; x < w; x++) { let r = 0 let g = 0 let b = 0 let a = 0 for (let dy = 0; dy < factor; dy++) { for (let dx = 0; dx < factor; dx++) { const d = ((y * factor + dy) * img.width + (x * factor + dx)) * 4 const al = img.rgba[d + 3] r += img.rgba[d] * al g += img.rgba[d + 1] * al b += img.rgba[d + 2] * al a += al } } const o = (y * w + x) * 4 if (a === 0) { out[o] = out[o + 1] = out[o + 2] = out[o + 3] = 0 } else { out[o] = Math.round(r / a) out[o + 1] = Math.round(g / a) out[o + 2] = Math.round(b / a) out[o + 3] = Math.round(a / n) } } } return { width: w, height: h, rgba: out } } /** 统计「纯白且不透明」像素占比(用于自检底噪) */ export function opaqueWhiteRatio(img) { let n = 0 for (let i = 0; i < img.width * img.height; i++) { const d = i * 4 if (img.rgba[d + 3] > 250 && img.rgba[d] > 250 && img.rgba[d + 1] > 250 && img.rgba[d + 2] > 250) n++ } return n / (img.width * img.height) }