Put generated PNG image into JSZip

强颜欢笑 提交于 2019-12-05 14:47:45

When you use zip.file("hello.png", imgData) where imgData is a string, you tell JSZip to save an (unicode) string. Since it's not a textual content, you get a corrupted content. To fix that, you can do:

zip.file("hello.png", imgData, {binary: true})

As dandavis suggested, using a blob will be more efficient here. You can convert a canvas to a blob with canvas.toBlob:

screen.toBlob(function (blob) {
  zip.file("hello.png", blob);
});

The only caveat is that toBlob is asynchronous: you should disable the download button during that time (or else, if a user is quick enough or the browser slow enough, zip.file won't be executed and you will give an empty zip to your user).

document.getElementById("download_button").disabled = true;
screen.toBlob(function (blob) {
  zip.file("hello.png", blob);
  document.getElementById("download_button").disabled = false;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!