XeqtR
XeqtR

Reputation: 35

How to get "raw" image data using JavaScript?

I have a base64 encoding of a PNG image (the string starts with data:image/png;base64,). My understanding is that this a base64 representation of the image encoded in PNG. Is there a way to get the "raw" pixel by pixel binary of the image using Node.js?

Upvotes: 0

Views: 2132

Answers (2)

kg99
kg99

Reputation: 766

Try this. First remove "data:image/png;base64," from the string. i.e

const img = base64Data.replace(/^data:image\/png;base64,/, "");

Then convert the image from base64.

const imgBuf = Buffer.from(img, 'base64');

At this point we have the image in binary. We can then get the pixels. Try with this module https://github.com/scijs/get-pixels.

const getPixels = require("get-pixels");

getPixels(imgBuf, "image/png", function(err, pixels) {
    if (err) {
        console.log("Bad image path")
        return
    }
    console.log("got pixels")
});

Upvotes: 5

Junior Ngangeli
Junior Ngangeli

Reputation: 112

I think you can acheive that by doing so:

var b64str;
var buf = new Buffer(b64str, 'base64');

As Buffer objects are used to represent a fixed-length sequence of bytes

Upvotes: 0

Related Questions