[英]Convert base64 image data to image file in angularjs
在 angularjs 中将 base64 文件转换为图像时得到损坏的文件 谁能建议我如何在 angularjs 中将 base64 文件转换为图像
我正在使用这种方法将 base64 文件转换为图像
var imageBase64 = "image base64 data";
var blob = new Blob([imageBase64], {type: 'image/png'});
从这个 blob,您可以生成文件对象。
var file = new File([blob], 'imageFileName.png');
首先,您将 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'"
});
除了一点之外,您的代码看起来还可以:
您提供给 Blob 对象的数据不是 Blob 数据,而是 base64 编码的文本。 您应该在插入之前解码数据。
一旦我不知道您想要哪个 API,我将使用一个名为 decodeBase64 的伪函数,我们将理解它执行 Base64 编码的逆操作(在 web 中有许多此函数的实现)。
您的代码应如下所示:
// 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 的必要性。
在 Angular 8 中需要这个,所以我将答案稍微修改为打字稿并直接修改为文件,因为您拥有数据字符串中的 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://stackoverflow.com/a/35401651/1805974
我在这里发布答案的唯一原因是因为谷歌一直将我发送到此页面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.