在AngularJS中将base64图像数据转换为图像文件

7

在使用AngularJS将base64文件转换为图像时,出现了文件损坏的情况,请问有什么建议可以解决这个问题吗?

我正在使用以下方法将base64文件转换为图像:

var imageBase64 = "image base64 data";
var blob = new Blob([imageBase64], {type: 'image/png'});

通过这个 Blob,您可以生成文件对象。

var file = new File([blob], 'imageFileName.png');

你能接受我的答案吗? - byteC0de
3个回答

20

首先,将dataURL转换为Blob。执行以下操作

var blob = dataURItoBlob(imageBase64);

function dataURItoBlob(dataURI) {

            // convert base64/URLEncoded data component to raw binary data held in a string
            var byteString;
            if (dataURI.split(',')[0].indexOf('base64') >= 0)
                byteString = atob(dataURI.split(',')[1]);
            else
                byteString = unescape(dataURI.split(',')[1]);

            // separate out the mime component
            var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

            // write the bytes of the string to a typed array
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }

            return new Blob([ia], {type:mimeString});
        }

然后

var file = new File([blob], "fileName.jpeg", {
            type: "'image/jpeg'"
          });

3
我至少卡了一天才解决这个问题,而你的代码完美地运作了,应该将其作为被采纳的答案。 - Camilo Casadiego
2
谢谢兄弟,我卡了三天。你帮我节省了时间。 - Pullat Junaid

1

你的代码看起来没问题,除了一个地方:

你给Blob对象提供的数据不是blob数据,而是一个经过base64编码的文本。在插入之前,你应该对数据进行解码。

由于我不知道你想使用哪个API,我将使用一个名为decodeBase64的伪函数,我们将理解它执行Base64编码的相反操作(网上有很多这个函数的实现)。

你的代码应该像这样:

// base64 already encoded data
var imageBase64 = "image base64 data";

//this is the point you should use
decodedImage = decodeBase64(imageBase64)

//now, use the decodedData instead of the base64 one
var blob = new Blob([decodedImage], {type: 'image/png'});

///now it should work properly
var file = new File([blob], 'imageFileName.png');

无论如何,如果您尚未使用AngularJS,则我看不到在那里使用它的必要性。


我以类似的方式完成了它,但是得到了损坏的图像,无法读取和打开。 - Sagar Patel

1

我需要在Angular 8中使用这个,所以我稍微修改了答案,使用了typescript并直接写入文件,由于你从datastring中获取了mimetype,因此可以使用它来创建文件。

dataURItoBlob(dataURI : any, fileName : string) : File{

    // convert base64/URLEncoded data component to a file
    var byteString;
   if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
   else
       byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
       ia[i] = byteString.charCodeAt(i);
    }

    return new File([ia],fileName, {type:mimeString});
}

所有的功劳归功于@byteC0de,答案在此链接中:https://dev59.com/c5Hea4cB1Zd3GeqPpnzP#35401651

我在这里发布答案的唯一原因是谷歌一直把我引导到这个页面。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接