17

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?

0

6 Answers 6

41

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);
...
Sign up to request clarification or add additional context in comments.

3 Comments

I tried your function and got the error Uncaught Error: InvalidCharacterError: DOM Exception 5: An invalid or illegal character was specified, such as in an XML name. Any ideas?
dataURI string should include base64 header, something like "data:image/jpeg;base64," Please let me know how it goes with it. @Nyxynyx
6
  fetch("data:image/jpeg;base64," + base64Data)
    .then(res => res.blob())
    .then(blob => {
      console.log(blob);
      var url = window.URL.createObjectURL(blob);
    });

1 Comment

I get "Network request failed" when I try this.
3

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;
}

Comments

3

Please try this simple way

  fetch(base64).then(res => return res.blob()).then(blob => console.log(blob));

1 Comment

fetch with base64 working for iOS device but not working for android! have you any idea?
2
const loadedPreviev = "data:application/pdf;base64,JVBERi0xLjMKJeLjz9MKMS..."
const base64Response = await fetch(loadedPreview)
const newBlob = await base64Response.blob()

1 Comment

I found info what helped me here splunktool.com/…
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.