所以基本上我想在 zip 文件中添加一些图像并能够下载它。我有两个保存图像来源的变量——pic1 、 pic2 和一个用于保存 base64 字符串的全局变量basePic 。我有一个将图像转换为 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 文件中只有第二张图片两次,调用此函数后我必须提醒一些东西,因为没有basePic将是空的。我想修复此功能,以便能够轻松地将多个图像源转换为 base64 字符串。
1.如何使这个功能正常工作,input_url -> output_base64,有多个图像?
2.如何做到这一点,而无需在每次调用该函数后发出警报?