22

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.

7

1 Answer 1

26

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Hi, any idea how can I build that imageData array out of an array of pixels like [ ... [r, g, b], [5, 63, 255] ...]?
@Frondor, you just should use Jimp.rgbaToInt(r, g, b, a); to build a color in hex format.
Yeah, figured out after a few google searches. Thank you!
Note that this is a 5MB dependency for just "writing a file", which is pretty crazy. You're better off with something like pngjs
While pngjs can decode an indexed PNG, it does not export/encode indexed color palette PNGs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.