如何使用 PNGJS 库从 rgb 矩阵创建 png?

How to use PNGJS library to create png from rgb matrix?

我无法根据此处 https://github.com/niegowski/node-pngjs . The documentation gives an example on manipulating an existing PNG.
In order to sanity check I've been trying to give every pixel the same RGB value. I think this issue post is relevant as well https://github.com/niegowski/node-pngjs/issues/20 的文档创建 PNG 文件(编码)。这是我试过的代码

var pic = new PNG({
    width: cols,
    height: rows
});
console.log(pic.width, pic.height);

var writeStream = fs.createWriteStream('C:\Users\yako\desktop\out.png');
pic.pack().pipe(writeStream);
writeStream.on('parsed', function() {
    console.log('parsed');
});
writeStream.on('finish', function() {
    fs.createReadStream('C:\Users\yako\desktop\out.png')
    .pipe(new PNG({
        filterType: -1
    }))
    .on('parsed', function() {

        for (var y = 0; y < this.height; y++) {
            for (var x = 0; x < this.width; x++) {
                var idx = (this.width * y + x) << 2;


                this.data[idx] = 255;
                this.data[idx+1] = 218;
                this.data[idx+2] = 185;


                this.data[idx+3] = 0.5;
            }
        }

        this.pack().pipe(fs.createWriteStream('C:\Users\yako\desktop\newOut.png'));
    });
});
writeStream.on('error', function (err) {
    console.error(err);
});

简单:

var fs = require('fs'),
    PNG = require('pngjs').PNG;

var png = new PNG({
    width: 100,
    height: 100,
    filterType: -1
});

for (var y = 0; y < png.height; y++) {
    for (var x = 0; x < png.width; x++) {
        var idx = (png.width * y + x) << 2;
        png.data[idx  ] = 255; // red
        png.data[idx+1] = 218; // green
        png.data[idx+2] = 185; // blue
        png.data[idx+3] = 128; // alpha (0 is transparent)
    }
}

png.pack().pipe(fs.createWriteStream('newOut.png'));