Is is possible to read pixel data from base64 images?

Viewed 6048

So here I have a base64 encoded png image:

iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==

and I decoded it using atob(). It turns out to be:

PNG

IHDRo&åIDAT×cøÿÿ?Ã Ã Ð1ñXÍõ5ËÑIEND®B`

Is it possible to get out the color values from this string? (without using <canvas>)

PS: It seems like it is possible since I found a demo:
 http://labs.calyptus.eu/JSBin/Demo/Viewer.html
 But I am not sure how he did it.

3 Answers

It can be useful to do this without having to rely on canvas or the browser render cycle. For example, if you need to do this work in a headless environment like a unit test runner.

This is possible with the help of a library called png.js

const PNGReader = require('png.js');

function parseDataImage(data: string) {
  console.log('Data is', data); // Data is data:image/png;base64,iVBORw0KGgoAAAANSUh...
  const base64 = data.split(',')[1];
  console.log('Base64 is', base64); // Base64 is iVBORw0KGgoAAAANSUh...
  const bytes = atob(base64); // Base64 Decode
  console.log('Bytes are', bytes); // Bytes are <Some binary data>
  const png = new PNGReader(bytes);
  png.parse((err, png) => {
    console.log('Pixels are', png.pixels); // Pixels are Buffer{0: 255, 1: 0, 2: 65, ...
  });
}
Related