【发布时间】:2017-09-24 04:07:32
【问题描述】:
我正在尝试从从另一个图像剪切的 base64 图像创建一个文件对象。我能够做到,但生成的文件大小几乎是实际大小的三倍。以下是我正在使用的功能:
convertDataURItoFile(dataURI, fileName) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob: any = new Blob([ia], { type: mimeString });
//A Blob() is almost a File() - it's just missing the two properties below which we will add
blob.lastModifiedDate = new Date();
blob.name = fileName;
//Cast to a File() type
return <File>blob;
}
知道为什么文件大小会急剧增加吗?我怎样才能压缩它?提前致谢。
【问题讨论】:
-
“生成的文件大小几乎是实际大小的三倍” 您如何确定生成的
Blob的大小不同?如果要设置.name和.lastModifiedDate为什么不使用File构造函数?File继承自Blob,Blob不继承自File。 -
无法重现生成的
Blob,其中.size大于通过data URI的内容。尽管请注意,生成的Blob与传递的data URI的数据内容不同。您能否创建一个 stacksn-ps 或 plnkr plnkr.co 来演示“生成的文件大小几乎是实际大小的三倍”?见stackoverflow.com/help/mvce
标签: javascript image file blob