Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
Nyxynyx Avatar asked Jan 16 '15 09:01

Nyxynyx


5 Answers

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);
...
like image 109
Nick Song Avatar answered Sep 23 '22 09:09

Nick Song


  fetch("data:image/jpeg;base64," + base64Data)
    .then(res => res.blob())
    .then(blob => {
      console.log(blob);
      var url = window.URL.createObjectURL(blob);
    });
like image 43
Md Shahriar Avatar answered Sep 23 '22 09:09

Md Shahriar


Please try this simple way

  fetch(base64).then(res => return res.blob()).then(blob => console.log(blob));
like image 38
Gopala raja naika Avatar answered Sep 23 '22 09:09

Gopala raja naika


In short, you can use the following function but if you want more details about this, you can read this post Create a blob from base64 data

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
 
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        const slice = byteCharacters.slice(offset, offset + sliceSize);
 
        const byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
 
        const byteArray = new Uint8Array(byteNumbers);
 
        byteArrays.push(byteArray);
    }
 
    const blob = new Blob(byteArrays, {type: contentType});
    return blob;
}
like image 25
Mustafa Dwekat Avatar answered Sep 27 '22 09:09

Mustafa Dwekat


I have the same problem. The reason for me is that there is space in the base64 string.
base64Str = base64Str.replace(/\s/g, '')

This solved my problem

like image 29
YuXitong Avatar answered Sep 23 '22 09:09

YuXitong