首页 > 解决方案 > JSZip 创建损坏的 JPG 图像

问题描述

我正在尝试将使用 html2canvas 创建的 JPG 图像添加到使用 JSZip 的 Zip 文件中。当我保存原始 JPG 文件时,结果很好。但是当我压缩它时,图像出现损坏(当我打开图像文件时,没有数据出现)。这是我的脚本:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://stuk.github.io/jszip/dist/jszip.js"></script>
        <script src="http://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
        <script type="text/javascript" src="FileSaver.min.js"></script>
    </head>
    <body>
        <div id="capture" style="padding: 0; background: #f5da55; width: 400px; height: 200px;">
            <h4 style="color: #000; ">Hello, world!</h4>
        </div>

        <script type="text/javascript">
            html2canvas( document.querySelector("#capture") ).then(canvas => {
                var img = new Image(); img.src = canvas.toDataURL( 'image/jpeg' );

                // * * * This JPG is good:    
                saveAs( img.src, 'file1.jpg');

                var zip = new JSZip();

                // Add a file to the zip file, in this case an image with data URI as contents
                // * * * This JPG comes out corrupted:    
                zip.file( 'file2.jpg', img.src, {binary: true} );

                // Generate the zip file asynchronously
                zip.generateAsync({type:"blob"}).then(function(content) {
                    saveAs( content, 'archive.zip' );
                });
            });
        </script>
    </body>
</html>

请帮我将数据 URI 图像添加到 zip 文件中。非常感谢!

标签: javascriptjszip

解决方案


我最终回答了我自己的问题。解决方案是首先将 Base64 数据 URI 图像转换为 BLOB。为此,我使用了以下自定义函数:

function dataURItoBlob( dataURI ) {
    // Convert Base64 to raw binary data held in a string.

    var byteString = atob(dataURI.split(',')[1]);

    // Separate the MIME component.
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    // Write the bytes of the string to an ArrayBuffer.
    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    // Write the ArrayBuffer to a BLOB and you're done.
    var bb = new Blob([ab]);

    return bb;
}

var image = dataURItoBlob( img.src );

Drewness 的建议也有效,但我更喜欢我的方法,因为 canvas.toBlob() 不返回值。


推荐阅读