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

标签 javascript node.js image-processing png

我无法根据此处的文档创建 PNG 文件(编码)https://github.com/niegowski/node-pngjs .该文档提供了一个操作现有 PNG 的示例。
为了完整性检查,我一直在尝试为每个像素赋予相同的 RGB 值。我认为这个问题帖子也很相关https://github.com/niegowski/node-pngjs/issues/20 .这是我试过的代码

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'));

关于javascript - 如何使用 PNGJS 库从 rgb 矩阵创建 png?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32259142/

相关文章:

c - 具有非中心起源的内核的 2D 卷积

javascript - 如何将元素列表放置在搜索输入下方

javascript - 一段时间后调用函数但只有一次

javascript - useEffect 在 react v18 中被调用两次

node.js - 错误 429 - 请求过多 - 尝试删除 IBM Watson Visual Recognition 服务的所有分类器

python - 图像噪声处理和边缘方向确定

数量级的 JavaScript 底数

node.js - 如何在sails 0.9中提供 Bootstrap 模板?

node.js - 在 macOS 终端中找不到 Google Lighthouse 命令

algorithm - 结构光 - 投影仪分辨率低于图案怎么办?