Is it possible to create a PNG image from a pixel data array using Node.js? I'd like to create a PNG image from an array of RGBA values, and then save it to a file.
-
I'd check Google first: github.com/pkrumins/node-pngBlender– Blender2012-09-12 03:33:05 +00:00Commented Sep 12, 2012 at 3:33
-
I also found this: github.com/pkrumins/node-imageAnderson Green– Anderson Green2012-09-12 03:34:32 +00:00Commented Sep 12, 2012 at 3:34
-
Which libPNG package will I need to install in order to use node-png?Anderson Green– Anderson Green2012-09-12 03:36:45 +00:00Commented Sep 12, 2012 at 3:36
-
It's the libpng library. Most Linux distributions ship with it: libpng.org/pub/png/libpng.htmlBlender– Blender2012-09-12 03:39:22 +00:00Commented Sep 12, 2012 at 3:39
-
1I found an exact duplicate of this question: stackoverflow.com/questions/7062812/…Anderson Green– Anderson Green2012-09-23 19:21:57 +00:00Commented Sep 23, 2012 at 19:21
|
Show 2 more comments
1 Answer
You can use jimp.
const Jimp = require('jimp');
let imageData = [
[ 0xFF0000FF, 0xFF0000FF, 0xFF0000FF ],
[ 0xFF0000FF, 0x00FF00FF, 0xFF0000FF ],
[ 0xFF0000FF, 0xFF0000FF, 0x0000FFFF ]
];
let image = new Jimp(3, 3, function (err, image) {
if (err) throw err;
imageData.forEach((row, y) => {
row.forEach((color, x) => {
image.setPixelColor(color, x, y);
});
});
image.write('test.png', (err) => {
if (err) throw err;
});
});
This code creates a png file 3x3 pixels with the colors defined in the array.
5 Comments
Frondor
Hi, any idea how can I build that
imageData array out of an array of pixels like [ ... [r, g, b], [5, 63, 255] ...]?Byte
@Frondor, you just should use
Jimp.rgbaToInt(r, g, b, a); to build a color in hex format.Frondor
Yeah, figured out after a few google searches. Thank you!
Mike 'Pomax' Kamermans
Note that this is a 5MB dependency for just "writing a file", which is pretty crazy. You're better off with something like pngjs
Kevin McDowell
While pngjs can decode an indexed PNG, it does not export/encode indexed color palette PNGs.