在Node.js中读取PNG图像 [英] Reading a PNG image in Node.js
问题描述
Node.js中是否有一种简单的方法来读取PNG文件并获取图像的像素?类似 node-image 的东西,但是相反:)
Is there an easy way in Node.js to read a PNG file and get the pixels of the image? Something like node-image, but the other way :)
我浏览了 https://github.com/joyent/node/wiki/中列出的库modules#wiki-graphics ,但是它们要么是提供裁剪和调整大小的命令行工具的简单包装,要么是诸如node-canvas
的复杂绘图工具.
I went through the libraries listed at https://github.com/joyent/node/wiki/modules#wiki-graphics, but they are either simple wrappers around command line tools providing cropping and resizing or complex drawing tools like node-canvas
.
推荐答案
该程序无需本地依赖即可进行PNG解码和编码:
This one does both PNG decoding and encoding without native dependancies:
pngjs-Node.js的PNG编码器/解码器,没有本地依赖性.
反转PNG颜色的示例:
An example for inverting the colors of a PNG:
var fs = require('fs'),
PNG = require('pngjs').PNG;
fs.createReadStream('in.png')
.pipe(new PNG())
.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;
// invert color
this.data[idx] = 255 - this.data[idx];
this.data[idx+1] = 255 - this.data[idx+1];
this.data[idx+2] = 255 - this.data[idx+2];
// and reduce opacity
this.data[idx+3] = this.data[idx+3] >> 1;
}
}
this.pack().pipe(fs.createWriteStream('out.png'));
});
这篇关于在Node.js中读取PNG图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!