javascript - 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 文件中。非常感谢!
解决方案
我最终回答了我自己的问题。解决方案是首先将 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() 不返回值。
推荐阅读
- android - Kml 图层与谷歌地图 latlngBounds 的交集
- telerik - 带有 Kendo 控件的 Web 实时预览问题
- python - Sense Hat - 检查时间操纵杆持有
- c# - 使用 ef core 迁移遗留数据非常慢
- node.js - Mongoose ValidationError 使 Express Server 崩溃
- html - 使用 Materialise Grids 将 2 行输入字段放在一列中
- cmake - 在 macos 上找不到带有 Ceres 的架构 x86_64 的符号
- javascript - 使用 Ajax 传递参数时 Laravel 405 错误
- python - 如何在 Django 的登录和注册表单中添加错误消息
- stripe-payments - 在设置 data.account 时,条带扩展 BankAccountListOptions 中的 Account 对象不起作用