来自链接: js批量下载图片并压缩打包.
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> img{ width: 200px; height: 150px; } </style> </head> <body> <!-- 注意图片的路径和项目域名必须不能存在跨域情况 例如:项目部署在 域名为 www.baidu.com/index.html 那么图片路径应改为 www.baidu.com/img/2.png --> <img src="img/2.png" /> <img src="img/3.png" /> <img src="img/1.jpeg" /> <br /><br /> <button onclick="packageImages()">packageImages</button><span id="status"></span><br /><br /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script> <script type="text/javascript"> function packageImages(){ $('#status').text('处理中。。。。。'); var imgs = $('img'); var imgsSrc = []; var imgBase64 = []; var imageSuffix = [];//图片后缀 var zip = new JSZip(); zip.file("readme.txt", "案件详情资料\n"); var img = zip.folder("images"); for(var i=0;i<imgs.length;i++){ var src = imgs[i].getAttribute("src"); var suffix = src.substring(src.lastIndexOf(".")); imageSuffix.push(suffix); getBase64(imgs[i].getAttribute("src")) .then(function(base64){ imgBase64.push(base64.substring(22)); },function(err){ console.log(err);//打印异常信息 }); } function tt(){ setTimeout(function(){ if(imgs.length == imgBase64.length){ for(var i=0;i<imgs.length;i++){ img.file(i+imageSuffix[i], imgBase64[i], {base64: true}); } zip.generateAsync({type:"blob"}).then(function(content) { saveAs(content, "images.zip"); }); $('#status').text('处理完成。。。。。'); }else{ $('#status').text('已完成:'+imgBase64.length+'/'+imgs.length); tt(); } },100); } tt(); } //传入图片路径,返回base64 function getBase64(img){ function getBase64Image(img,width,height) { var canvas = document.createElement("canvas"); canvas.width = width ? width : img.width; canvas.height = height ? height : img.height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); var dataURL = canvas.toDataURL(); return dataURL; } var image = new Image(); image.crossOrigin = 'Anonymous'; image.src = img; var deferred=$.Deferred(); if(img){ image.onload =function (){ deferred.resolve(getBase64Image(image)); } return deferred.promise(); } } </script> </body> </html>