Skip to content
Advertisement

Converting base64 to blob in javascript

I tried to convert a JPEG’s base64 string to a blob on a Cordova/hybrid app running on iOS 8 using the following function b64toBlob.

b64toBlob = function(b64, onsuccess, onerror) {
    var img = new Image();

    img.onerror = onerror;

    img.onload = function onload() {
        var canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);

        canvas.toBlob(onsuccess);
    };

    img.src = b64;
}

However it’s giving an error

Uncaught Error: TypeError: undefined is not a function (evaluating 'canvas.toBlob(onsuccess)')

when we do

var imageData = "data:image/jpeg;base64," + imageData

b64toBlob(imageData,
    function(imageBlob) {
       uploadBlob(imageBlob)
    }, function(error) {
        console.log(error)
    });

How can be work around this error?

Advertisement

Answer

Try this out. Please note that dataURI is assumed to include base64 prefix. (e.g. "data:image/jpeg;base64,")

function b64toBlob(dataURI) {
    
    var byteString = atob(dataURI.split(',')[1]);
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    return new Blob([ab], { type: 'image/jpeg' });
}

Usage:

...

var blob = b64toBlob(imageData);

var formData = new FormData();
formData.append("source", blob);
...
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement