基本上我想将几张图片添加到zip文件中并能够下载它。我有两个变量分别保存图像的来源-pic1, pic2和一个全局变量basePic来保存base64字符串。我有一个将图像转换为base64的函数:
var pic; //http://www.somesite.com/i/picture.jpg
var pic2; //http://www.somesite.com/i/picture2.jpg
var basePic;// base64 string of an image
function getBase64FromImageUrl(url) {
var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function () {
var canvas = document.createElement("canvas");
canvas.width =this.width;
canvas.height =this.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL("image/png");
basePic=dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
};
img.src = url; // I was trying to put this after setAttribute, but it's the same effect
}
稍后我会尝试创建一个zip文件,并像这样调用该函数:
var zip = new JSZip();
getBase64FromImageUrl(pic);
alert("random text"); // without it, it's just empty file added to zip
zip.file("picture.png",basePic, {base64: true});
getBase64FromImageUrl(pic2);
alert("random text");
zip.file("picture2.png",basePic, {base64: true});
zip.generateAsync({type:"blob"})
.then(function(content) {
saveAs(content, "example.zip");
});
这个函数可以使用一张图片,但是如果有多张图片,它就变得更加随机。如果我在不刷新页面的情况下运行代码几次,可能会得到我需要的结果。但大多数时候,在我的 zip 文件中只有第二张图片出现了两次,而且我必须在调用该函数后alert一些东西,因为没有basePic将为空。我想修复此函数,以使其能够轻松地将多个图像源转换为 base64 字符串。
1.如何使此函数按预期工作,输入 url -> 输出 base64,同时处理多个图像?
2.如何在每次调用该函数时无需警报某些内容?