Convert base64 to file nodejs

There might be scenarios where you need to convert an base64 string back to a file. This article will show you how.

The high level view

As an example, a base64 string representation of a png image looks like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...

To convert it back to an image, we need to:

  • Strip off the data:image/png;base64, part
  • Write the remaining string to a file using a base64 encoding.

The code

I am using:

let base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA'; 


let base64Image = base64String.split[';base64,'].pop[];

To write to a file

I am using:

import fs from 'fs';

fs.writeFile['image.png', base64Image, {encoding: 'base64'}, function[err] {
console.log['File created'];
}];

Don’t forget the {encoding: 'base64'} here and you will be good to go.

UPDATE

I found this interesting link how to solve your problem in PHP. I think you forgot to replace space by +as shown in the link.

I took this circle from //images-mediawiki-sites.thefullwiki.org/04/1/7/5/6204600836255205.png as sample which looks like:

Next I put it through //www.greywyvern.com/code/php/binary2base64 which returned me:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAAAAACPAi4CAAAAB3RJTUUH1QEHDxEhOnxCRgAAAAlwSFlzAAAK8AAACvABQqw0mAAAAXBJREFUeNrtV0FywzAIxJ3+K/pZyctKXqamji0htEik9qEHc3JkWC2LRPCS6Zh9HIy/AP4FwKf75iHEr6eU6Mt1WzIOFjFL7IFkYBx3zWBVkkeXAUCXwl1tvz2qdBLfJrzK7ixNUmVdTIAB8PMtxHgAsFNNkoExRKA+HocriOQAiC+1kShhACwSRGAEwPP96zYIoE8Pmph9qEWWKcCWRAfA/mkfJ0F6dSoA8KW3CRhn3ZHcW2is9VOsAgoqHblncAsyaCgcbqpUZQnWoGTcp/AnuwCoOUjhIvCvN59UBeoPZ/AYyLm3cWVAjxhpqREVaP0974iVwH51d4AVNaSC8TRNNYDQEFdlzDW9ob10YlvGQm0mQ+elSpcCCBtDgQD7cDFojdx7NIeHJkqi96cOGNkfZOroZsHtlPYoR7TOp3Vmfa5+49uoSSRyjfvc0A1kLx4KC6sNSeDieD1AWhrJLe0y+uy7b9GjP83l+m68AJ72AwSRPN5g7uwUAAAAAElFTkSuQmCC

saved this string to base64 which I read from in my code.

var fs      = require['fs'],
data        = fs.readFileSync['base64', 'utf8'],
base64Data,
binaryData;

base64Data  =   data.replace[/^data:image\/png;base64,/, ""];
base64Data  +=  base64Data.replace['+', ' '];
binaryData  =   new Buffer[base64Data, 'base64'].toString['binary'];

fs.writeFile["out.png", binaryData, "binary", function [err] {
    console.log[err]; // writes out file without error, but it's not a valid image
}];

I get a circle back, but the funny thing is that the filesize has changed :]...

END

When you read back image I think you need to setup headers

Take for example imagepng from PHP page:


I think the second line header['Content-Type: image/png'];, is important else your image will not be displayed in browser, but just a bunch of binary data is shown to browser.

In Express you would simply just use something like below. I am going to display your gravatar which is located at //www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG and is a jpeg file when you curl --head //www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG. I only request headers because else curl will display a bunch of binary stuff[Google Chrome immediately goes to download] to console:

curl --head "//www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
HTTP/1.1 200 OK
Server: nginx
Date: Wed, 03 Aug 2011 12:11:25 GMT
Content-Type: image/jpeg
Connection: keep-alive
Last-Modified: Mon, 04 Oct 2010 11:54:22 GMT
Content-Disposition: inline; filename="cabf735ce7b8b4471ef46ea54f71832d.jpeg"
Access-Control-Allow-Origin: *
Content-Length: 1258
X-Varnish: 2356636561 2352219240
Via: 1.1 varnish
Expires: Wed, 03 Aug 2011 12:16:25 GMT
Cache-Control: max-age=300
Source-Age: 1482
$ mkdir -p ~/tmp/6922728
$ cd ~/tmp/6922728/
$ touch app.js

app.js

var app = require['express'].createServer[];

app.get['/', function [req, res] {
    res.contentType['image/jpeg'];
    res.sendfile['cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG'];
}];

app.get['/binary', function [req, res] {
    res.sendfile['cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG'];
}];

app.listen[3000];

$ wget "//www.gravatar.com/avatar/cabf735ce7b8b4471ef46ea54f71832d?s=32&d=identicon&r=PG"
$ node app.js

How do I convert from base 64 to PDF?

Features.
Fast and Easy Conversion. Upload your document, choose the save format type and click on “Convert” button. You will get the download link as soon as the file is converted..
Convert from Anywhere. It works from all platforms including Windows, Mac, Android and iOS. ... .
Conversion Quality..

Is BTOA deprecated?

These functions btoa and atob are deprecated for Node JS. If you are coding for the web browser you just need to prepend the window to get rid of this deprecation mark. Otherwise, you could install buffer with "yarn add buffer" or "npm i buffer" to run on browser.

How do I decrypt base64?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.

Can base64 string compress?

1 Answer. Show activity on this post. Base64 is already encoded in a way which does not suit most compression algorithms - see Why does base64-encoded data compress so poorly? for details. You will want to compress the original binary data and then base64 the compressed data, or don't bother converting to base64 at all ...

Chủ Đề