<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> img{ width: 200px; height: 150px; } </style> </head> <body> <img src="http://img.zcool.cn/community/01c92f56597f686ac7251c94e76e51.jpg" /> <img src="http://img.zcool.cn/community/01888f5922bad7b5b3086ed4cc3711.jpg" /> <br /><br /> <button οnclick="packageImages()">packageImages</button><span id="status"></span><br /><br /> <script src="http://stuk.github.io/jszip/test/jquery-1.8.3.min.js"></script> <script type="text/javascript" src="https://stuk.github.io/jszip/dist/jszip.js"></script> <script type="text/javascript" src="http://stuk.github.io/jszip/vendor/FileSaver.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)); //console.log(base64);//处理成功打印在控制台 }, 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) { // see FileSaver.js saveAs(content, "images.zip"); }); $('#status').text('处理完成。。。。。'); } else { //console.log('imgs.length:'+imgs.length+',imgBase64.length:'+imgBase64.length); $('#status').text('已完成:' + imgBase64.length + '/' + imgs.length); tt(); } }, 100); } tt(); } //传入图片路径,返回base64 function getBase64(img) { function getBase64Image(img, width, height) {//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));//将base64传给done上传处理 } return deferred.promise();//问题要让onload完成后再return sessionStorage['imgTest'] } } </script> </body> </html>
JS批量打包下载图片 (转载)
最新推荐文章于 2024-05-16 19:13:54 发布