Skip to content

Instantly share code, notes, and snippets.

@ijse
Created November 14, 2013 08:52
Show Gist options
  • Save ijse/7463591 to your computer and use it in GitHub Desktop.
Save ijse/7463591 to your computer and use it in GitHub Desktop.
Very useful for resizing images before upload using html5 canvas.
/**
* Convert base64 encode image into Blob
*
* Usage:
* var dataURL = canvas.toDataURL('image/jpeg', 0.5);
* var blob = dataURItoBlob(dataURL);
* var fd = new FormData(document.forms[0]);
* fd.append("canvasImage", blob);
*
* See: http://stackoverflow.com/a/5100158/1063090
*/
function dataURItoBlob(dataURI, isURLEncoded) {
var byteString;
if(isURLEncoded) {
// convert base64/URLEncoded data component to raw binary data held in a string
if (dataURI.split(',')[0].indexOf('base64') >= 0)
byteString = atob(dataURI.split(',')[1]);
else
byteString = unescape(dataURI.split(',')[1]);
} else {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs
byteString = atob(dataURI.split(',')[1]);
}
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var bb = new BlobBuilder();
bb.append(ab);
return bb.getBlob(mimeString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment