来自base64字符串的Javascript图像

时间:2017-01-31 21:23:11

标签: javascript image base64

api给我发送base64字符串,表示有图像。 我有一个函数将此字符串转换为blob存储。

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

当我用atob(b64Data)转换我的字符串时,我有这个错误:

  

错误无法在'Window'上执行'atob':要解码的字符串未正确编码。

我的编码字符串以这种方式开始:

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

我如何在javascript中解码这个?我尝试使用在线转换器(从base64到图像)的字符串,并正常工作。

由于

2 个答案:

答案 0 :(得分:0)

您只需使用字符串即可显示图像

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

答案 1 :(得分:0)

您可以尝试以下操作:(您可以看到代码有效 here
javascript文件:

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

}
}