如何使用JavaScript在PNG文件中无损插入任意自定义数据
实现方案
PNG格式原生支持插入符合规范的辅助数据块,不会破坏图像本身的像素数据,也不需要使用隐写术。你可以使用PNG标准定义的tEXt文本块存储自定义JSON数据,所有常规图片查看器都可以正常渲染该PNG文件,嵌入的内容仅在你主动读取时才会被解析。
前置依赖说明
所有操作均基于PNG官方规范实现,无需引入任何第三方库,可直接在浏览器端的UserScript环境运行。
步骤1:从Canvas获取原始PNG二进制数据
// 从Canvas元素导出PNG格式的二进制流 async function getCanvasPngBuffer(canvas: HTMLCanvasElement): Promise<ArrayBuffer> { const blob = await new Promise<Blob | null>(resolve => canvas.toBlob(resolve, 'image/png')); if (!blob) throw new Error('Canvas导出PNG失败'); return blob.arrayBuffer(); }
步骤2:实现PNG块操作工具函数
PNG块需要CRC校验保证完整性,先实现CRC32计算工具:
// 预生成CRC32计算表 const CRC32_TABLE = new Uint32Array(256); for (let i = 0; i < 256; i++) { let c = i; for (let j = 0; j < 8; j++) { c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; } CRC32_TABLE[i] = c; } // 计算二进制数据的CRC32值 function crc32(data: Uint8Array): number { let crc = 0xffffffff; for (const byte of data) { crc = CRC32_TABLE[(crc ^ byte) & 0xff] ^ (crc >>> 8); } return (crc ^ 0xffffffff) >>> 0; }
步骤3:向PNG插入自定义文本块
function insertPngTextChunk(pngBuffer: ArrayBuffer, keyword: string, content: string): ArrayBuffer { const uint8 = new Uint8Array(pngBuffer); // 校验PNG文件签名 const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; for (let i = 0; i < 8; i++) { if (uint8[i] !== PNG_SIGNATURE[i]) throw new Error('非法PNG文件'); } // 构造tEXt块内容:关键字 + 0分隔符 + 文本内容 const keywordBytes = new TextEncoder().encode(keyword); const contentBytes = new TextEncoder().encode(content); const chunkData = new Uint8Array(keywordBytes.length + 1 + contentBytes.length); chunkData.set(keywordBytes, 0); chunkData.set([0], keywordBytes.length); chunkData.set(contentBytes, keywordBytes.length + 1); // 构造完整PNG块结构:长度 + 块类型 + 数据 + CRC校验 const chunkType = new TextEncoder().encode('tEXt'); const chunkLength = new Uint8Array(4); new DataView(chunkLength.buffer).setUint32(0, chunkData.length, false); const crcInput = new Uint8Array([...chunkType, ...chunkData]); const crc = new Uint8Array(4); new DataView(crc.buffer).setUint32(0, crc32(crcInput), false); const customChunk = new Uint8Array([...chunkLength, ...chunkType, ...chunkData, ...crc]); // 定位插入位置:IHDR块之后,IDAT图像数据块之前 let offset = 8; // 跳过PNG签名 const ihdrLength = new DataView(uint8.buffer).getUint32(offset, false); offset += 4 + 4 + ihdrLength + 4; // 跳过整个IHDR块 // 拼接生成新的PNG二进制流 const newPng = new Uint8Array(uint8.length + customChunk.length); newPng.set(uint8.subarray(0, offset), 0); newPng.set(customChunk, offset); newPng.set(uint8.subarray(offset), offset + customChunk.length); return newPng.buffer; }
步骤4:导出嵌入穿搭数据的PNG文件
async function exportOutfitPng(canvas: HTMLCanvasElement, outfitData: object) { const rawPngBuffer = await getCanvasPngBuffer(canvas); const jsonContent = JSON.stringify(outfitData); // 自定义关键字为OUTFIT_DATA,后续读取时用该关键字匹配 const embeddedPngBuffer = insertPngTextChunk(rawPngBuffer, 'OUTFIT_DATA', jsonContent); // 触发浏览器下载 const blob = new Blob([embeddedPngBuffer], { type: 'image/png' }); const url = URL.createObjectURL(blob); const downloadLink = document.createElement('a'); downloadLink.href = url; downloadLink.download = '我的穿搭.png'; downloadLink.click(); URL.revokeObjectURL(url); }
步骤5:读取PNG中嵌入的穿搭数据
function readPngTextChunk(pngBuffer: ArrayBuffer, targetKeyword: string): string | null { const uint8 = new Uint8Array(pngBuffer); const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]; for (let i = 0; i < 8; i++) { if (uint8[i] !== PNG_SIGNATURE[i]) throw new Error('非法PNG文件'); } let offset = 8; while (offset < uint8.length) { const chunkLength = new DataView(uint8.buffer).getUint32(offset, false); const chunkType = new TextDecoder().decode(uint8.subarray(offset + 4, offset + 8)); if (chunkType === 'IEND') break; // 遍历到文件尾结束 if (chunkType === 'tEXt') { const data = uint8.subarray(offset + 8, offset + 8 + chunkLength); const separatorIndex = data.findIndex(b => b === 0); if (separatorIndex !== -1) { const keyword = new TextDecoder().decode(data.subarray(0, separatorIndex)); if (keyword === targetKeyword) { return new TextDecoder().decode(data.subarray(separatorIndex + 1)); } } } // 跳过当前块继续遍历 offset += 4 + 4 + chunkLength + 4; } return null; } // 导入PNG读取穿搭数据示例 async function loadOutfitFromPng(file: File): Promise<object | null> { const buffer = await file.arrayBuffer(); const jsonStr = readPngTextChunk(buffer, 'OUTFIT_DATA'); return jsonStr ? JSON.parse(jsonStr) : null; }
可选优化
如果你的穿搭JSON数据体积较大,可以改用PNG标准支持的zTXt块存储压缩后的内容,只需将块类型改为zTXt,对JSON内容做zlib压缩后再写入即可,读取逻辑对应调整即可。
内容的提问来源于stack exchange,提问作者Nato Boram
相关产品推荐
相关产品推荐

