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

How CSS affects the white screen time during initial loading

Rendering pipeline with external css files In the...

Use of nginx custom variables and built-in predefined variables

Overview Nginx can use variables to simplify conf...

Detailed example of using js fetch asynchronous request

Table of contents Understanding Asynchrony fetch(...

Monitor changes in MySQL table content and enable MySQL binlog

Preface binlog is a binary log file, which record...

About dynamically adding routes based on user permissions in Vue

Display different menu pages according to the use...

Detailed explanation of the use of MySQL group links

Grouping and linking in MYSQL are the two most co...

A brief analysis of Linux network programming functions

Table of contents 1. Create a socket 2. Bind sock...

How to hide rar files in pictures

You can save this logo locally as a .rar file and...

Html easily implements rounded rectangle

Question: How to achieve a rounded rectangle usin...

Introduction to the deletion process of B-tree

In the previous article https://www.jb51.net/arti...

Two ways to specify the character set of the html page

1. Two ways to specify the character set of the h...

React ref usage examples

Table of contents What is ref How to use ref Plac...

The difference between absolute path and relative path in web page creation

1. Absolute path First of all, on the local compu...

Definition and function of zoom:1 attribute in CSS

Today I was asked what the zoom attribute in CSS ...

In-depth understanding of CSS @font-face performance optimization

This article mainly introduces common strategies ...