javascript 在javascript中将base64转换为blob

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27980612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:14:44  来源:igfitidea点击:

Converting base64 to blob in javascript

javascriptioshtmlcordovacanvas

提问by Nyxynyx

I tried to convert a JPEG's base64 string to a blob on a Cordova/hybrid app running on iOS 8 using the following function b64toBlob.

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

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

However it's giving an error

但是它给出了一个错误

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

when we do

当我们做

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

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

How can be work around this error?

如何解决此错误?

回答by filipvkovic

Try this out. Please note that dataURIis assumed to include base64 prefix. (ex: "data:image/jpeg;base64,")

试试这个。请注意,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' });
}

Usage:

用法:

...

var blob = b64toBlob(imageData);

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

回答by Mustafa Dwekat

In short, you can use the following function but if you want more details about this, you can read this post Create a blob from base64 data

简而言之,您可以使用以下功能,但如果您想了解更多有关此功能的详细信息,您可以阅读这篇文章从 base64 数据创建一个 blob

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

回答by YuXitong

I have the same problem. The reason for me is that there is space in the base64 string.
base64Str = base64Str.replace(/\s/g, '')

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

This solved my problem

这解决了我的问题

回答by Gopala raja naika

Please try this simple way

请试试这个简单的方法

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