Skip to content Skip to sidebar Skip to footer

Is Is Possible To Read Pixel Data From Base64 Images?

So here I have a base64 encoded png image: iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg== and I decoded it us

Solution 1:

In the source of the page you pointed, there's a function that uses the PNG.js and some other utilities to do what you want:

functionshow(data){
    var png = newPNG(data);
    var img = document.getElementById('image'), limg = document.getElementById('largeimage');
    document.getElementById('nativeimage').src = 'data:image/png;base64,' + data;
    img.innerHTML = '';
    limg.innerHTML = '';
    img.style.width = png.width + 'px';
    img.style.height = png.height + 'px';
    limg.style.width = (png.width * 3) + 'px';
    limg.style.width = (png.height * 3) + 'px';
    var line;
    while(line = png.readLine())
    {
        for (var x = 0; x < line.length; x++){
            var px = document.createElement('div'), px2 = document.createElement('div');
            px.className = px2.className = 'pixel';
            px.style.backgroundColor = px2.style.backgroundColor = '#' + line[x].toString(16).padRight('0', 6);
            img.appendChild(px);
            limg.appendChild(px2);
        }
    }
}

If you look at the loop in this function , you will notice that it's reading the PNG, line by line and ploting the pixels.

A simplified example would be:

var png = newPNG(data); // data is the base64 encoded datavar line;
var y = 0;
while(line = png.readLine())
{
    for (var x = 0; x < line.length; x++){
        var pixel = doSomethingWithPixelData(x, y, '#' + line[x].toString(16).padRight('0', 6));
    }
    y++;
}

functiondoSomethingWithPixelData(x, y, color) {
    // guess what? do something with pixel data here ;)
}

Solution 2:

No, you cannot get the color values from that string directly. You must decode the PNG image data somehow (it is compressed). Using <canvas> is one way to do that.

Solution 3:

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

constPNGReader = require('png.js');

functionparseDataImage(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 Decodeconsole.log('Bytes are', bytes); // Bytes are <Some binary data>const png = newPNGReader(bytes);
  png.parse((err, png) => {
    console.log('Pixels are', png.pixels); // Pixels are Buffer{0: 255, 1: 0, 2: 65, ...
  });
}

Post a Comment for "Is Is Possible To Read Pixel Data From Base64 Images?"