美文网首页
react.js批量导出图片

react.js批量导出图片

作者: Ropynn | 来源:发表于2020-04-02 17:00 被阅读0次

    完整代码

    import JSZip from 'jszip'
    import FileSaver from 'file-saver'
    import { message } from 'antd';
    
    function getBase64Image(img) {
        let canvas = document.createElement('canvas');
        canvas.width = img.width;
        canvas.height = img.height;
        let ctx = canvas.getContext('2d');
        ctx.drawImage(img, 0, 0, img.width, img.height);
        let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase();
        return canvas.toDataURL('image/' + ext);
    }
    
    //传入图片路径,返回base64
    function getBase64(img) {
        let image = new Image();
        image.setAttribute('crossOrigin', 'anonymous'); // 必须设置在src之前,跨域使用
        image.src = img;
        return new Promise((resolve) => {
            if (img) {
                image.onload = () => {
                    resolve(getBase64Image(image));
                }
            }
        })
    }
    
    export default function toZip(imgSrcList, fileName) {
        let imgBase64 = [];
        let imageSuffix = [];//图片后缀
        let zip = new JSZip();  //实例化一个压缩文件对象
        let imgFolder = zip.folder(fileName); //新建一个图片文件夹用来存放图片,参数为文件名
        for (let i = 0; i < imgSrcList.length; i++) {
            let src = imgSrcList[i];
            let suffix = src.substring(src.lastIndexOf('.'));
            imageSuffix.push(suffix);
            getBase64(src)
                .then(base64 => imgBase64.push(base64.substring(22)))
                .catch(error => console.log('error', error))
        }
    
        function polling() {
            setTimeout(() => {
                if (imgSrcList.length === imgBase64.length) {
                    for (let i = 0; i < imgSrcList.length; i++) {
                        imgFolder.file(i + imageSuffix[i], imgBase64[i], { base64: true });
                    }
                    zip.generateAsync({ type: 'blob' }).then(function (content) {
                        FileSaver.saveAs(content, `${fileName}.zip`);
                    });
                    message.destroy()
                    message.success('打包完成')
                } else {
                    console.log('已完成:' + imgBase64.length + '/' + imgSrcList.length)
                    polling();
                }
            }, 300);
        }
    
        polling();
    }
    
    

    使用方法

    import toZip from 'utils/jszip'
    
    toZip(imgSrcList, fileName)
    

    相关文章

      网友评论

          本文标题:react.js批量导出图片

          本文链接:https://www.haomeiwen.com/subject/kzoxphtx.html