Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScrip 打包(zip)批量下载页面图片 #21

Open
lzpong opened this issue Sep 22, 2022 · 1 comment
Open

JavaScrip 打包(zip)批量下载页面图片 #21

lzpong opened this issue Sep 22, 2022 · 1 comment

Comments

@lzpong
Copy link
Owner

lzpong commented Sep 22, 2022

  1. 加载打包JS JSZip.js
//加载 zip.js
function loadJS( fileUrl ){
  var oHead = document.getElementsByTagName("HEAD").item(0);
  var oScript= document.createElement("script");
  oScript.type = "text/javascript";
  oScript.src=fileUrl ;
  oHead.appendChild( oScript);
}
loadJS("https://stuk.github.io/jszip/dist/jszip.js")
  1. 下载函数 (此函数针对 img.src="data:image/jpeg;base64,xxxxxxx" 的图片, 或此格式的 img.src 数组)
//打包下载(压缩包名,img数组), 此函数针对 img.src="data:image/jpeg;base64,xxxxxxx" 的图片
function downAllImg(name,imgArray){
  //创建一个JSZip实例,官方网址:https://stuk.github.io/jszip/
  var zip = new JSZip();
  //使用.folder(folderName)添加一个文件夹
  var dir = zip.folder(name);
  // 向zip文件中添加图片,可以添加多个文件或者图片,此处以图片为例
  // base64图片需要去掉base64图片标识
  //zip.file("car.jpg", imgData.substring(imgData.indexOf(",") + 1), {base64: true});
  //使用.file(fileName,fileContent,base64FLag)在文件夹下添加一个图片文件
  imgArray.forEach(function(e){
    let src=e.src||e;src=src.substring(src.indexOf(",") + 1);
    dir.file((new Date().toISOString()).replace(/:/g,'-')+"_"+Math.floor(Math.random()*100)+".jpg", src, {base64: true});
  });
  zip.generateAsync({
    type: "blob",  // 压缩类型, 压缩的结果为二进制流,可用作文件上传
    compression: "DEFLATE",  // STORE:默认不压缩 DEFLATE:需要压缩
    compressionOptions: {
        level: 9  // 压缩等级1~9    1压缩速度最快,9最优压缩方式
        // [使用一张图片测试之后1和9压缩的力度不大,相差100字节左右]
    }
  }).then(function (content) {
    // 压缩的结果为blob类型(二进制流),可用作文件上传
    console.info(content);
    // 直接在浏览器打成car.zip包并下载,saveAs依赖的js是FileSaver.js
    //saveAs(content, "car.zip");
    var s=document.createElement("a");
    if(content instanceof Blob)
    s.href = URL.createObjectURL(content);
    else s.href="data:application/zip;base64," + content;
    s.download=name+".zip";
    document.body.appendChild(s);
    s.click(),document.body.removeChild(s)
  });
}
  1. 使用
//img.src="data:image/jpeg;base64,xxxxxxx" 的格式,不是图片地址
downAllImg("图片打包下载",document.querySelectorAll('img'))
downAllImg("图片打包下载",["data:image/jpeg;base64,xxxxxxx","data:image/jpeg;base64,xxxxxxx","data:image/jpeg;base64,xxxxxxx"])

  1. 下载混合图片数据 (此函数针对 img.src="http://xxxxxx" 的图片数据 或 img.src="http://" 的图片地址)
//打包下载图片,可以是图片数据,或者是图片地址的数组
function downAllImg(name,imgArray){
var datalist=[],urllist=[],urllistcount=0;
imgArray.forEach(function(e){let src=e.src||e;if(src.startsWith("data:"))datalist.push(src);else urllist.push(src)})
if(urllist.length<1) packAndSave(name,datalist);
else downUrls(null,true);
//所有url下载
function downUrls(d,a){
  if(a){
    urllist.forEach(function(u){ downUrl1(u, downUrls) })
  }else{
     urllistcount=urllist.length;
    datalist.push(d);
    if(urllistcount>=urllist.length) packAndSave(name,datalist);
  }
}
//不带跨域
function downUrl1(url,cb){
  var x=new XMLHttpRequest();
  x.open("GET", url, true);
  x.responseType = 'blob';
  x.onload=function(e){
    cb(window.URL.createObjectURL(x.response))
  }
  x.send();
}
//带跨域
function downUrl2(url,cb) {
  var image = new Image();
  // 解决跨域 Canvas 污染问题
  image.setAttribute("crossOrigin", "anonymous");
  // 或者这个
  //imgge.crossOrigin = "Access-Control-Allow-Origin";
  image.onload = function() {
    var canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    var context = canvas.getContext("2d");
    context.drawImage(image, 0, 0, image.width, image.height);
    cb(canvas.toDataURL("image/png",0.7)); //得到图片的base64编码数据
  };
  image.src = url;
}
//打包保存
function packAndSave(name,imgDataArray){
  //创建一个JSZip实例,官方网址:https://stuk.github.io/jszip/
  var zip = new JSZip();
  //使用.folder(folderName)添加一个文件夹
  var dir = zip.folder(name);
  // 向zip文件中添加图片,可以添加多个文件或者图片,此处以图片为例
  // base64图片需要去掉base64图片标识
  //zip.file("car.jpg", imgData.substring(imgData.indexOf(",") + 1), {base64: true});
  //使用.file(fileName,fileContent,base64FLag)在文件夹下添加一个图片文件
  imgDataArray.forEach(function(e){
    let src=e.src||e;src=src.substring(src.indexOf(",") + 1);
    dir.file((new Date().toISOString()).replace(/:/g,'-')+"_"+Math.floor(Math.random()*10000)+".jpg", src, {base64: true});
  });
  zip.generateAsync({
    type: "blob",  // 压缩类型, 压缩的结果为二进制流,可用作文件上传
    compression: "DEFLATE",  // STORE:默认不压缩 DEFLATE:需要压缩
    compressionOptions: {
        level: 9  // 压缩等级1~9    1压缩速度最快,9最优压缩方式
        // [使用一张图片测试之后1和9压缩的力度不大,相差100字节左右]
    }
  }).then(function (content) {
    // 压缩的结果为blob类型(二进制流),可用作文件上传
    console.info(content);
    // 直接在浏览器打成car.zip包并下载,saveAs依赖的js是FileSaver.js
    //saveAs(content, "car.zip");
    var s=document.createElement("a");
    if(content instanceof Blob)
    s.href = URL.createObjectURL(content);
    else s.href="data:application/zip;base64," + content;
    s.download=name+".zip";
    document.body.appendChild(s);
    s.click(),document.body.removeChild(s)
  });
}
}
@lzpong
Copy link
Owner Author

lzpong commented Feb 20, 2023

(()=>{
function loadjs(url){
  var j=document.createElement("script");
  j.type="text/javascript";j.src=url;
  document.head.appendChild(j);
}
['/dist/jszip.js','-utils/dist/jszip-utils.js','/vendor/FileSaver.js'].forEach(x=>loadjs('https://stuk.github.io/jszip'+x));

var arr=document.querySelectorAll(".entry-content img");
var Fname=document.querySelector(".entry-title").innerText;
const zip = new JSZip()
//const fileFolder = zip.folder(Fname) // 创建 zipName 子文件夹
var pics=[];
const fileList = []

function getImg(url,i){
  i=i||0;
  JSZipUtils.getBinaryContent(url,(err,file)=>{
    //console.log(a,b)
    if(err==null){
      fileList.push({ name: url.substr(url.lastIndexOf('/')+1), img: file});
      console.log(fileList.length , arr.length)
      down();
    }
    else if(i<3) getImg(url,++i);
    else console.error(err,url,"3's try")
  })
}

function down(){
  if (fileList.length && fileList.length === arr.length) {
    console.log(Fname)
    for (let k = 0; k < fileList.length; k++) {
      // 往文件夹中,添加每张图片数据
      //fileFolder.file(fileList[k].name, fileList[k].img, {base64: true}) 现不需要添加到子文件夹中
      zip.file(fileList[k].name, fileList[k].img, {base64: true})
    }
    var json={name:Fname,dir:location.hostname,url:location.href,urls:pics,referer:location.origin};
    zip.file("pics.json",JSON.stringify(json));
    zip.file(Fname+'.url',"[InternetShortcut]\r\nURL="+json.url);
    zip.generateAsync({ type: 'blob' }).then(content =>{ saveAs(content, Fname + '.zip') })
  }
}

/**
 * 批量下载图片, 等待js资源加载
 */
setTimeout(()=>{
arr.forEach(x=>{
  var src=x.dataset.src;
  getImg(src)
  pics.push(src);
})
},2000)
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant