Last active
August 10, 2023 14:37
-
-
Save barbietunnie/5fa07012925ee0fe53a0 to your computer and use it in GitHub Desktop.
Decode base64 image in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} |
@orestotel any update?
Guys, this is node.js code. It won't work in the browser.
A little late. Works perfectly. Just change obsolete 'Buffer(matches[2],' to 'Buffer.from(matches[2],'
A little late. Works perfectly. Just change obsolete 'Buffer(matches[2],' to 'Buffer.from(matches[2],'
Updated. Thanks
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
Please, write working code.
https://jsfiddle.net/dnug7ofz/