将 base64 字符串转换为 blob。使用文件上传器的文件是具有额外属性的 blob,因此上传 blob 的工作方式相同。
var file = dataURItoBlob(canString, 'image/png');
function dataURItoBlob(dataURI, type) {
// convert base64 to raw binary data held in a string
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 bb = new Blob([ab], { type: type });
return bb;
}
UPDATE
要将 Base64 字符串转换为图像:
var image = new Image(),
containerWidth = null,
containerHeight = null;
image.onload=function(){
containerWidth = image.width;
containerHeight = image.height;
}
image.src = base64string;
或者将 Base64 字符串本地保存为文件(当我找到实现它的位置时,该文件不在内存中):
function saveImage(base64string) {
var imageData = base64string.split(',')[1];
var a = $("<a>").attr("href", "data:Application/base64," + imageData )
.attr("download","image.png")
.appendTo("body");
a[0].click();
a.remove();
}