How to convert grayscale image matrix to image in Node.js

谁都会走 提交于 2019-12-24 17:48:50

问题


I have a matrix of values representing an 8-bit grayscale image (values range from 0 to 255). I would like to display this image on the web. How can I do so? The image is coming from a C program, would this require converting the image in the C program?


回答1:


I ended up using the pngjs library to do the job thanks to stdob's suggestion https://www.npmjs.com/package/pngjs. Heres the code I used:

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;
        png.data[idx+1] = 218;
        png.data[idx+2] = 185;
        png.data[idx+3] = 255;
    }
}

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


来源:https://stackoverflow.com/questions/32188260/how-to-convert-grayscale-image-matrix-to-image-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!