-
-
Save barbietunnie/5fa07012925ee0fe53a0 to your computer and use it in GitHub Desktop.
/** | |
* 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; | |
} |
Please, write working code.
https://jsfiddle.net/dnug7ofz/
@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
Error: Buffer is not defined