Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Last active August 10, 2023 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barbietunnie/5fa07012925ee0fe53a0 to your computer and use it in GitHub Desktop.
Save barbietunnie/5fa07012925ee0fe53a0 to your computer and use it in GitHub Desktop.
Decode base64 image in javascript
/**
* Decode base64 image
*.e.g. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAPAQMAAABeJUoFAAAABlBMVEX///8AAABVwtN+AAAAW0lEQVQImY2OMQrAMAwDjemgJ3jI0CFDntDBGKN3hby9bWi2UqrtkJAk8k/m5g4vGBCprKRxtzQR3mrMlm2CKpjIK0ZnKYiOjuUooS9ALpjV2AjiGY3Dw+Pj2gmnNxItbJdtpAAAAABJRU5ErkJggg==
*/
function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
response = {};
if (matches.length !== 3) {
return new Error('Invalid input string');
}
response.type = matches[1];
response.data = Buffer.from(matches[2], 'base64');
return response;
}
@neilbannet
Copy link

Error: Buffer is not defined

@orestotel
Copy link

Please, write working code.
https://jsfiddle.net/dnug7ofz/

@Sathishchary
Copy link

@orestotel any update?

@VictorGorban
Copy link

Guys, this is node.js code. It won't work in the browser.

@sean-sayed
Copy link

A little late. Works perfectly. Just change obsolete 'Buffer(matches[2],' to 'Buffer.from(matches[2],'

@barbietunnie
Copy link
Author

A little late. Works perfectly. Just change obsolete 'Buffer(matches[2],' to 'Buffer.from(matches[2],'

Updated. Thanks

@volod5000
Copy link

volod5000 commented Aug 10, 2023

Here is a working example.
To make it work, I used the 'npm i buffer' package

/**

  • Decode base64 image
    *.e.g. data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAPAQMAAABeJUoFAAAABlBMVEX///8AAABVwtN+AAAAW0lEQVQImY2OMQrAMAwDjemgJ3jI0CFDntDBGKN3hby9bWi2UqrtkJAk8k/m5g4vGBCprKRxtzQR3mrMlm2CKpjIK0ZnKYiOjuUooS9ALpjV2AjiGY3Dw+Pj2gmnNxItbJdtpAAAAABJRU5ErkJggg==
    */

       function decodeBase64Image(dataString) {
               var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),  response = {};
       
               if (matches.length !== 3) {
                   return new Error('Invalid input string');
               }
       
               response.type = matches[1];
               let buf = Buffer.from(matches[2]);
               response.data = new Blob(buf, {type: matches[1]});
       
               return response
        }
    

Wrote under React
The output is a :blob, with all the attributes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment