在 javascript 中将 base64 转换为 blob

Converting base64 to blob in javascript

我尝试使用以下函数 b64toBlob.[=15= 将 JPEG 的 base64 字符串转换为 iOS 8 上 运行 应用程序 运行 ]

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

但是报错

Uncaught Error: TypeError: undefined is not a function (evaluating 'canvas.toBlob(onsuccess)')

当我们这样做时

var imageData = "data:image/jpeg;base64," + imageData

b64toBlob(imageData,
    function(imageBlob) {
       uploadBlob(imageBlob)
    }, function(error) {
        console.log(error)
    });

如何解决这个错误?

试试这个。请注意 dataURI 假定包含 base64 前缀。 (例如 "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' });
}

用法:

...

var blob = b64toBlob(imageData);

var formData = new FormData();
formData.append("source", blob);
...

简而言之,您可以使用以下功能,但如果您想了解更多详细信息,可以阅读此 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;
}

我也遇到了同样的问题。我的原因是base64字符串中有space.
base64Str = base64Str.replace(/\s/g, '')

这解决了我的问题

请试试这个简单的方法

  fetch(base64).then(res => return res.blob()).then(blob => console.log(blob));
  fetch("data:image/jpeg;base64," + base64Data)
    .then(res => res.blob())
    .then(blob => {
      console.log(blob);
      var url = window.URL.createObjectURL(blob);
    });