Nodejs - 仅使用 FS 和 ZLIB 模块编写和编码 PNG 文件

Nodejs - Writing and encoding a PNG file with only FS and ZLIB modules

我正在尝试从十六进制颜色字符串 (#RRGGBB) 生成 .png 图像,而不使用像 pngjs or jimp.

这样的模块

十六进制字符串如下所示:

let colors = "ff000000ff000000ffff00ff00ffffffff00";

根据 this article,所有 png 文件必须以签名 b'\x89PNG\r\n\x1a\n' 开头并具有 3 个“块”(IHDR、IDAT 和 IEND),每个块具有以下结构:

(数据长度、块类型、块数据和 CRC)

并且根据png specs, it is compressed with zlib's deflate,所以我想出了这个代码:

const fs = require("fs");
const zlib = require("zlib");

let colors = "ff000000ff000000ffff00ff00ffffffff00";
let data = `b'\x89PNG\r\n\x1a\n'0d00IHDR030002008200000002400IDAT${colors}0000IEND`;

zlib.deflateRaw(data, (err, buffer) => {
    fs.writeFile("output.png", buffer, (err)=>{if (err) throw err;});
});

为了更好的可读性,拆分数据如下所示:

b'\x89PNG\r\n\x1a\n' // signature
0d00 // chunk data length (13)
IHDR // chunk type

/* chunk data */
0300 // image width (3)
0200 // image height (2)
8 // bit depth (8)
2 // color type (2)
0 // compression method (0)
0 // filter method (0)
0 // interlace method (0)
0000 // CRC (?)

2400 // chunk data length (36)
IDAT // chunk type
ff000000ff000000ffff00ff00ffffffff00 // chunk data (#RRGGBB)
0000 // CRC (?)
IEND

我期望得到的结果是下面的图像(3x2 大小),但我只有一个看似无效的 png 文件,我的图像查看器不支持它。

这样写一个有效的png文件真的可行吗?如果是,怎么做?

PNG 中的那些像素(您需要显着放大才能看到六个像素):

十六进制转储:

89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52
00 00 00 03 00 00 00 02 08 02 00 00 00 12 16 f1
4d 00 00 00 17 49 44 41 54 08 99 63 f8 cf c0 c0
f0 9f 81 81 e1 3f 0b 94 fe cf 08 00 39 04 06 00
83 e9 a9 e3 00 00 00 00 49 45 4e 44 ae 42 60 82