在 Node.js 中读取 PNG 图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11247790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a PNG image in Node.js
提问by Jan ?pa?ek
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 :)
Node.js 中是否有一种简单的方法来读取 PNG 文件并获取图像的像素?类似于node-image,但另一种方式:)
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.
我浏览了https://github.com/joyent/node/wiki/modules#wiki-graphics 中列出的库,但它们要么是命令行工具的简单包装器,提供裁剪和调整大小,要么是复杂的绘图工具,如node-canvas.
回答by P.D.P.
This one does both PNG decoding and encoding without native dependancies:
这个可以在没有原生依赖的情况下进行 PNG 解码和编码:
pngjs - PNG encoder/decoder for Node.js with no native dependencies.
pngjs - Node.js 的 PNG 编码器/解码器,没有本机依赖项。
An example for inverting the colors of a PNG:
反转 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'));
});
回答by Alba Mendez
I was about to became mad searching, but I found one:
我正要疯狂搜索,但我找到了一个:
png.js― A PNG decoder in JS for the canvas element or Node.js.
png.js― 用于画布元素或 Node.js 的 JS PNG 解码器。
var PNG = require('png-js');
var myimage = new PNG('myimage.png');
var width = myimage.width;
var height = myimage.height;
myimage.decode(function (pixels) {
//Pixels is a 1D array containing pixel data
});
Please note it's pureJavaScript. Works both in the browser<canvas>and in Node.JS.
请注意它是纯JavaScript。适用于浏览器<canvas>和Node.JS。
There are more properties apart from widthand height, see this source.
除了widthand之外还有更多属性height,请参阅此来源。
回答by Peter Grundmann
I think
我认为
var myimage = new PNG('myimage.png');
should be
应该
var myimage = new PNG.load('myimage.png');

