Last active
December 11, 2023 07:21
-
-
Save jdnichollsc/78a6eb093731cf3e8dfd536dbe4befb3 to your computer and use it in GitHub Desktop.
Convert to Blob with 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
//By https://codedump.io/share/Fd3DmsM6UAeS/1/creating-a-blob-from-a-base64-string-in-javascript | |
//Example | |
//var blob = b64toBlob(b64Data, contentType); | |
//var blobUrl = URL.createObjectURL(blob); | |
function b64toBlob(b64Data, contentType, sliceSize) { | |
contentType = contentType || 'image/png'; | |
sliceSize = sliceSize || 512; | |
var byteCharacters = atob(b64Data); | |
var byteArrays = []; | |
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { | |
var slice = byteCharacters.slice(offset, offset + sliceSize); | |
var byteNumbers = new Array(slice.length); | |
for (var i = 0; i < slice.length; i++) { | |
byteNumbers[i] = slice.charCodeAt(i); | |
} | |
var byteArray = new Uint8Array(byteNumbers); | |
byteArrays.push(byteArray); | |
} | |
var blob = new Blob(byteArrays, {type: contentType}); | |
return blob; | |
} |
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
//Example var file = dataURLtoBlob(canvas.toDataURL()); | |
function dataURLtoBlob(dataURL) { | |
// Decode the dataURL | |
var binary = atob(dataURL.split(',')[1]); | |
// Create 8-bit unsigned array | |
var array = []; | |
for (var i = 0; i < binary.length; i++) { | |
array.push(binary.charCodeAt(i)); | |
} | |
// Return our Blob object | |
return new Blob([new Uint8Array(array)], { type: 'image/png' }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Real source: https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript