Jay Gould Jay Gould - 1 year ago 270
Javascript Question

Convert base64 image data to png?

I'm using Mapbox's Javascript PBF library to convert a

file to a
. For context, here's what I have so far:

var pbfFile = new pbf(fs.readFileSync('0.pbf')), // pbfFile.buf gives us the binary data for the image

buffer = new Uint8Array();
buffer = pbfFile.readBytes();

console.log("Raw Uint8 data: " + buffer);

var bufferToBase64 =btoa(String.fromCharCode.apply(null, buffer));

console.log("Image data in base64: " + bufferToBase64);

which outputs the following:

Raw Uint8 data: 139,8,0,0,0,0,0,0,3,157,86,123,84,84,199,25,223,111,230,238,222,185,23,88,150,187,168,184,32,44,23

Image data in base64: iwgAAAAAAAADnVZ7VFTHGd9v5u7euRdYlruouCAsFw==

I'm a little lost as to how I can convert the base64 data to a
image and pass it to my server. I have an
server running and listening to requests, right now the above code runs when I connect to it via terminal.

Is there a way I can convert the above base 64 and send the image to my browser? Not necessarily in a canvas, just as a file (thus prompting a download) is perfectly fine.

Answer Source

You can do this by using base64-img

Install it using npm

npm install base64-img --save


base64Img.img('data:image/png;base64,...', 'dest', '1', function(err, filepath) {});

Further documentation can be found here base64-img

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download