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的資料請關註WalkonNet其它相關文章!

推薦閱讀: