js realizes packaging multiple pictures into zip

js realizes packaging multiple pictures into zip

1. Import files

<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 page

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

3. Main code

function packageImages() {
    $('#status').text('Processing...')

    var imgsSrc = []

    // https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg
    // upload/2022/web/u=2151136234,3513236673&fm=26&gp=0.jpg
    for (var i = 0; i < 1; i++) {
        imgsSrc.push('upload/2022/web/O1CN01npzdZ52Cf3A4cx8JG_!!0-item_pic.jpg_240x240.jpg')
    }
    var imgBase64 = [] //base64 image var imageSuffix = [] //image suffix var zip = new JSZip()
    zip.file('readme.txt', 'Case details\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,/, ""))
                // When all images are converted to base64, perform image compression if (imgsSrc.length == imgBase64.length) {
                    for (var i = 0; i < imgsSrc.length; i++) {
                        // File name data 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('Processing completed...')
                    })
                }
            },
            function (err) {
                console.log(err) //Print exception information}
        )
    }
}

// Pass in the image path and return base64
function getBase64(img) {
    function getBase64Image(img, width, height) {
        //When calling width and height, pass in specific pixel values ​​to control the size. If not passed, the default image size will be used 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)) // pass base64 to done for upload processing}
        return deferred.promise() //The problem is to return sessionStorage['imgTest'] after onload is completed
    }
}

4. Optimize the process of converting images to base64 and improve the zip packaging speed

function packageImages() {
    $('#status').text('Processing...')

    var imgsSrc = []

    // https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg
    // upload/2022/web/u=2151136234,3513236673&fm=26&gp=0.jpg
    for (var i = 0; i < 1; i++) {
        imgsSrc.push('upload/2022/web/u=2496571732,442429806&fm=26&gp=0.jpg')
    }
    var imgBase64 = [] //base64 image var imageSuffix = [] //image suffix var zip = new JSZip()
    zip.file('readme.txt', 'Case details\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++) {
                    // File name data 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('Processing completed...')
                })
            }
        })
    }
}
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('Read error!')
            };
            fr.readAsDataURL(res); //If it is text conversion, the second parameter can use encoding})
}

5. Optimize again and convert the image to base64 through axios

function packageImages() {
    $('#status').text('Processing...')

    var imgsSrc = []

    // https://dss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2496571732,442429806&fm=26&gp=0.jpg
    // upload/2022/web/u=2151136234,3513236673&fm=26&gp=0.jpg
    for (var i = 0; i < 100; i++) {
        imgsSrc.push('upload/2022/web/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())
        })
    })
};

// Batch download 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) => { // Download the file and save it as an ArrayBuffer object const arr_name = item.split("/");
            let file_name = arr_name[arr_name.length - 1] // Get the file name // if (file_name.indexOf('.png') == -1) {
            // file_name = file_name + '.png'
            // }
            await zip.file(idx + '.png', data, {
                binary: true
            }) // Add files one by one })
        promises.push(promise)
    })
    Promise.all(promises).then(() => {
        zip.generateAsync({
            type: "blob"
        }).then(content => { // Generate binary stream saveAs(content, "photo.zip") // Use file-saver to save the file $('#status').text('Processing completed....')
        })
    })

};

The above is the details of how to use js to pack multiple pictures into zip. For more information about js pictures packing into zip, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of customizing the packaging path of css, js and pictures in vue-cli3.0
  • Release BlueShow v1.0 Image browser (similar to lightbox) blueshow.js package download
  • Usage and difference of Js module packaging exports require import
  • vue.config.js packaging optimization configuration
  • Teach you step by step how to compile and package video.js
  • nuxt.js adds environment variables to distinguish project packaging environment operations
  • vue solves the problem of uglifyjs-webpack-plugin packaging error
  • Summary of methods for compressing the volume of Vue.js after packaging (Vue.js is too large after packaging)
  • Solve the problem of vendor.js file being too large after vue packaging

<<:  How to change the password of mysql5.7.20 under linux CentOS 7.4

>>:  Detailed explanation of using Docker to quickly deploy the ELK environment (latest version 5.5.1)

Recommend

JavaScript explains the encapsulation and use of slow-motion animation

Implementing process analysis (1) How to call rep...

Detailed explanation of daily_routine example code in Linux

First look at the example code: #/bin/bash cal da...

Recommended 20 best free English handwriting fonts

Jellyka BeesAntique Handwriting [ank]* Jellyka Cut...

About Nginx gzip configuration

The principle of nginx to achieve resource compre...

HTML+CSS to create a top navigation bar menu

Navigation bar creation: Technical requirements: ...

js tag syntax usage details

Table of contents 1. Introduction to label statem...

How to use lodop print control in Vue to achieve browser compatible printing

Preface This control will have a watermark at the...

Detailed description of component-based front-end development process

Background <br />Students who work on the fr...

Nodejs module system source code analysis

Table of contents Overview CommonJS Specification...

JavaScript adds prototype method implementation for built-in objects

The order in which objects call methods: If the m...

Understanding and using React useEffect

Table of contents Avoid repetitive rendering loop...

Manually implement the two-way data binding principle of Vue2.0

In one sentence: Data hijacking (Object.definePro...