首页 > 编程语言 > js实现多张图片打包成zip
2021
07-22

js实现多张图片打包成zip

1、引入文件

<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jszip/3.6.0/jszip.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>

2、html页面

<button onclick="packageImages()">下载zip</button><span id="status"></span>

3、主要代码

function packageImages() {
    $('#status').text('处理中。。。。。')

    var imgsSrc = []

    // https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg
    // https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2151136234,3513236673&fm=26&gp=0.jpg
    for (var i = 0; i < 1; i++) {
        imgsSrc.push('https://img.alicdn.com/bao/uploaded/i1/446338500/O1CN01npzdZ52Cf3A4cx8JG_!!0-item_pic.jpg_240x240.jpg')
    }
    var imgBase64 = [] //base64图片
    var imageSuffix = [] //图片后缀
    var zip = new JSZip()
    zip.file('readme.txt', '案件详情资料\n')
    var img = zip.folder('images')

    for (var i = 0; i < imgsSrc.length; i++) {
        var suffix = imgsSrc[i].substring(imgsSrc[i].lastIndexOf('.'))
        imageSuffix.push(suffix)

        getBase64(imgsSrc[i]).then(
            function (base64) {
                console.log(base64)
                imgBase64.push(base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
                // 当所有图片转成base64执行图片压缩
                if (imgsSrc.length == imgBase64.length) {
                    for (var i = 0; i < imgsSrc.length; i++) {
                        // 文件名  数据
                        img.file(i + imageSuffix[i], imgBase64[i], {
                            base64: true,
                        })
                    }
                    zip.generateAsync({
                        type: 'blob'
                    }).then(function (content) {
                        console.log(1)
                        // see FileSaver.js
                        saveAs(content, 'images.zip')
                        $('#status').text('处理完成。。。。。')
                    })
                }
            },
            function (err) {
                console.log(err) //打印异常信息
            }
        )
    }
}

//传入图片路径,返回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']
    }
}

4、优化图片转base64的流程,提高zip的打包速度

function packageImages() {
    $('#status').text('处理中。。。。。')

    var imgsSrc = []

    // https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg
    // https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2151136234,3513236673&fm=26&gp=0.jpg
    for (var i = 0; i < 1; i++) {
        imgsSrc.push('https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg')
    }
    var imgBase64 = [] //base64图片
    var imageSuffix = [] //图片后缀
    var zip = new JSZip()
    zip.file('readme.txt', '案件详情资料\n')
    var img = zip.folder('images')

    for (var i = 0; i < imgsSrc.length; i++) {
        var suffix = imgsSrc[i].substring(imgsSrc[i].lastIndexOf('.'))
        imageSuffix.push(suffix)

        getBase64(imgsSrc[i], function (base64) {
            imgBase64.push(base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, ""))
            if (imgsSrc.length == imgBase64.length) {
                for (var i = 0; i < imgsSrc.length; i++) {
                    // 文件名  数据
                    img.file(i + imageSuffix[i], imgBase64[i], {
                        base64: true,
                    })
                }
                zip.generateAsync({
                    type: 'blob'
                }).then(function (content) {
                    console.log(1)
                    // see FileSaver.js
                    saveAs(content, 'images.zip')
                    $('#status').text('处理完成。。。。。')
                })
            }
        })
    }
}
function getBase64(img, callback) {
    fetch(img).then(
        res => res.blob())
        .then(res => {
            let fr = new FileReader();//https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
            fr.onload = function (e) {
                callback(e.target.result)
            };
            fr.onerror = function () {
                console.log('读取错误!')
            };
            fr.readAsDataURL(res);//如果是转文字,第二个参数可以使用编码
        })
}

5、再优化,通过axios把图片转成base64

function packageImages() {
    $('#status').text('处理中。。。。。')

    var imgsSrc = []

    // https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg
    // https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2151136234,3513236673&fm=26&gp=0.jpg
    for (var i = 0; i < 100; i++) {
        imgsSrc.push('https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg')
    }

    handleBatchDownload(imgsSrc)
}



getFile = (url) => {
    return new Promise((resolve, reject) => {
        axios({
            method: 'get',
            url,
            responseType: 'arraybuffer'
        }).then(data => {
            resolve(data.data)
        }).catch(error => {
            reject(error.toString())
        })
    })
};

// 批量下载
handleBatchDownload = async (selectImgList) => {
    const data = selectImgList;
    const zip = new JSZip()
    const promises = []
    await data.forEach((item, idx) => {
        // console.log(item, idx)
        const promise = this.getFile(item).then(async (data) => { // 下载文件, 并存成ArrayBuffer对象
            const arr_name = item.split("/");
            let file_name = arr_name[arr_name.length - 1] // 获取文件名
            // if (file_name.indexOf('.png') == -1) {
            //    file_name = file_name + '.png'
            // }
            await zip.file(idx + '.png', data, {
                binary: true
            }) // 逐个添加文件
        })
        promises.push(promise)
    })
    Promise.all(promises).then(() => {
        zip.generateAsync({
            type: "blob"
        }).then(content => { // 生成二进制流
            saveAs(content, "photo.zip") // 利用file-saver保存文件
            $('#status').text('处理完成。。。。。')
        })
    })

};

以上就是js实现多张图片打包成zip的详细内容,更多关于js 图片打包成zip的资料请关注自学编程网其它相关文章!

编程技巧