1
votes

I try to convert base64 to blob but got error of Uncaught InvalidCharacterError: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

I tested my base64 image data here http://codebeautify.org/base64-to-image-converter and it worked fine, I'm able to see the image rendered fine

 function b64toBlob(b64Data, contentType, sliceSize) {
            contentType = contentType || '';
            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;
        }

      var blob = b64toBlob(base64Data, 'image/jpeg'); 
      console.log(blob)

https://jsfiddle.net/wfh5fjn9/

1

1 Answers

1
votes

What happened is that you kept data:image/jpeg;base64, in the string of base64Data. You need to remove it and only keep the string that is actually base64 encoded for it to work.

In other words,

var base64Data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQ' // truncated

becomes

var base64Data = '/9j/4AAQSkZJRgABAQ' // truncated

https://jsfiddle.net/wfh5fjn9/1/