0
votes

an api give send me base64 string that there is an image. I have a function that traslate this string to blob storage.

function b64toPhoto(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 512;

        //var byteCharacters = atob(b64Data);
        var byteCharacters = atob(b64Data.replace(/^data:image\/(png|jpg);base64,/, '')); 

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

When I convert my string with atob(b64Data), I have this error:

Error failed to execute 'atob' on 'Window': the string to be decoded is not correctly encoded.

My encoded string start in this way:

/9j/4AAQSkZJRgABAgAAAQABAAD/7QCuUGhvdG9zaG9wIDMuMAA4Qk....

How I can decode this in javascript? I try my string with online converter (from base64 to image) and work fine.

Thanks

2
There must be something wrong with b64Data, otherwise you wouldn't get that error. Maybe it has something at the end that you didn't paste into the online converter.Barmar

2 Answers

0
votes

You can simply use the string to display image

var image = new Image();
image.src = '<string received>...';
document.body.appendChild(image);
0
votes

you can try this:(you can see the code works here)
javascript file:

function getTextToDecode () {


//get the encoded string 
var valuToDecode = document.getElementById("userCode").value;
//this is just for making the decoded image downloadable
var linkImg = valuToDecode.concat('" alt="Red dot" download="ganixo-file.png"> click here to download your img </a>');
document.getElementById("codedImg").innerHTML=  '<a href="data:image/jpeg;base64,'.concat(linkImg);
if (valuToDecode == "") {
    alert("text area is empty ! try again..");
}else{
//this is the answer for your question
//check if there is any errors
    if(!atob(valuToDecode))
        {
            alert("bad format! try again..")
        }else
        {
            //decode the encoded string
            var decodedString = atob(valuToDecode);
           //make the image downloadable
            document.getElementById("decodeResult").value = decodedString;
        }
    

}
}