使用jszip这个项目实现的:https://github.com/Stuk/jszip
FileSaver.js项目地址是:https://github.com/eligrey/FileSaver.js/
<script src="./FileSaver.min.js"></script>
<script src="./jszip.min.js"></script>
// 初始化一个zip打包对象
var zip = new JSZip();
// 创建一个被用来打包的名为Hello.txt的文件
zip.file("Hello.txt", "Hello World\n");
// 创建一个名为images的新的文件目录
var img = zip.folder("images");
// 这个images文件目录中创建一个base64数据为imgData的图像,图像名是smile.gif
img.file("smile.gif", imgData, {base64: true});
// 把打包内容异步转成blob二进制格式
zip.generateAsync({type:"blob"}).then(function(content) {
// content就是blob数据,这里以example.zip名称下载
// 使用了FileSaver.js
saveAs(content, "example.zip");
});
url转base64
Promise 实现
export function getUrlBase64(url) {
return new Promise((resolve, reject) => {
let canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
let img = new Image();
img.crossOrigin = "Anonymous"; //解决Canvas.toDataURL 图片跨域问题
img.src = url;
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0, img.width, img.height); //参数可自定义
const dataURL = canvas.toDataURL("image/jpeg", 1); //获取Base64编码
resolve(dataURL);
canvas = null; //清除canvas元素
img = null; //清除img元素
};
img.onerror = function () {
reject(new Error("Could not load image at " + url));
};
});
}
回调函数实现
export function getUrlBase64Callback(url, callback) {
let canvas = document.createElement("canvas"); //创建canvas DOM元素
const ctx = canvas.getContext("2d");
const img = new Image();
img.crossOrigin = "Anonymous";
img.src = url;
img.onload = function () {
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0, img.width, img.height);
const dataURL = canvas.toDataURL("image/jpeg", 1); //可选取多种模式
callback.call(this, dataURL); //回掉函数获取Base64编码
canvas = null;
};
}
标签:canvas,zip,img,url,base64,height,width
From: https://www.cnblogs.com/idolmaster-765pro/p/17495657.html