将生成的PNG图片放入JSZip
Put generated PNG image into JSZip
我正在使用 JSZip 制作一个程序,该程序从 canvas 元素生成图像数据并将图像放入 zip 文件中。
目前,它正在将 canvas 图像转换为 DataURL。然后,我去掉了结果字符串中 data:image/png;base64,
的部分。现在,只剩下 base64 数据了。然后我使用 atob
将其更改为 ascii。
似乎将剩余的字符串放入图像文件应该可以,但生成的 ascii 文本不正确。很多地方都是对的,但也有不对的地方。
这是我的代码:
//screen is the name of the canvas.
var imgData = screen.toDataURL();
imgData = imgData.substr(22);
imgData = atob(imgData);
console.log(imgData);
这是生成的 png 文件的图像(在记事本中):
incorrect text http://upurs.us/image/71280.png
这是应该的样子:
correct text http://upurs.us/image/71281.png
如您所见,存在细微差异,我不知道为什么。我对 PNG 文件类型或 ASCII 完全一无所知,所以我不知道从这里去哪里。
如果你想看我所有的作品,这里是项目:
http://s000.tinyupload.com/download.php?file_id=09682586927694868772&t=0968258692769486877226111
编辑:我的最终目标是有一个程序可以导出 canvas 动画的每一帧,这样我就可以用它们制作视频。如果有人知道这样做的程序,请 post 它!
当您使用 zip.file("hello.png", imgData)
时,其中 imgData
是一个字符串,您告诉 JSZip 保存一个 (unicode) 字符串。由于它不是文本内容,因此您会得到损坏的内容。要解决这个问题,您可以这样做:
zip.file("hello.png", imgData, {binary: true})
正如 dandavis 所建议的,在这里使用 blob 会更有效。您可以使用 canvas.toBlob:
将 canvas 转换为 blob
screen.toBlob(function (blob) {
zip.file("hello.png", blob);
});
唯一需要注意的是 toBlob
是异步的:您应该在此期间禁用下载按钮(否则,如果用户足够快或浏览器足够慢,zip.file
将不会t 被执行,你将给你的用户一个空的 zip。
document.getElementById("download_button").disabled = true;
screen.toBlob(function (blob) {
zip.file("hello.png", blob);
document.getElementById("download_button").disabled = false;
});
我正在使用 JSZip 制作一个程序,该程序从 canvas 元素生成图像数据并将图像放入 zip 文件中。
目前,它正在将 canvas 图像转换为 DataURL。然后,我去掉了结果字符串中 data:image/png;base64,
的部分。现在,只剩下 base64 数据了。然后我使用 atob
将其更改为 ascii。
似乎将剩余的字符串放入图像文件应该可以,但生成的 ascii 文本不正确。很多地方都是对的,但也有不对的地方。
这是我的代码:
//screen is the name of the canvas.
var imgData = screen.toDataURL();
imgData = imgData.substr(22);
imgData = atob(imgData);
console.log(imgData);
这是生成的 png 文件的图像(在记事本中): incorrect text http://upurs.us/image/71280.png
这是应该的样子: correct text http://upurs.us/image/71281.png
如您所见,存在细微差异,我不知道为什么。我对 PNG 文件类型或 ASCII 完全一无所知,所以我不知道从这里去哪里。
如果你想看我所有的作品,这里是项目: http://s000.tinyupload.com/download.php?file_id=09682586927694868772&t=0968258692769486877226111
编辑:我的最终目标是有一个程序可以导出 canvas 动画的每一帧,这样我就可以用它们制作视频。如果有人知道这样做的程序,请 post 它!
当您使用 zip.file("hello.png", imgData)
时,其中 imgData
是一个字符串,您告诉 JSZip 保存一个 (unicode) 字符串。由于它不是文本内容,因此您会得到损坏的内容。要解决这个问题,您可以这样做:
zip.file("hello.png", imgData, {binary: true})
正如 dandavis 所建议的,在这里使用 blob 会更有效。您可以使用 canvas.toBlob:
将 canvas 转换为 blobscreen.toBlob(function (blob) {
zip.file("hello.png", blob);
});
唯一需要注意的是 toBlob
是异步的:您应该在此期间禁用下载按钮(否则,如果用户足够快或浏览器足够慢,zip.file
将不会t 被执行,你将给你的用户一个空的 zip。
document.getElementById("download_button").disabled = true;
screen.toBlob(function (blob) {
zip.file("hello.png", blob);
document.getElementById("download_button").disabled = false;
});