在javascript中将base64转换为blob

时间:2015-01-16 09:17:17

标签: javascript ios html5 cordova canvas

我尝试使用以下函数b64toBlob将JPEG的base64字符串转换为在iOS 8上运行的Cordova /混合应用程序上的blob。

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

如何解决此错误?

5 个答案:

答案 0 :(得分:6)

试试这个功能。请注意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);
...

答案 1 :(得分:3)

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

答案 2 :(得分:1)

我有同样的问题。对我来说,原因是base64字符串中有空格。
base64Str = base64Str.replace(/\s/g, '')

这解决了我的问题

答案 3 :(得分:1)

请尝试这种简单方式

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

答案 4 :(得分:0)

简而言之,您可以使用以下功能,但是如果您需要更多有关此功能的详细信息,可以阅读此帖子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;
}