Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving an image from canvas in a zip

I have a canvas in HTML5 that can end up being a very long dataURL (long enough to crash chrome if they try to navigate to it). Because of that, I'm trying to save the image in a zip using JSZip. I've tried the following two things:

var zip = new JSZip();
var savable = new Image();
savable.src = canvas.toDataURL();
zip.file("image.png", savable, {base64: true});
var content = zip.generate();
var blobLink = document.getElementById('blob');
blobLink.download = "image.zip";
blobLink.href = window.URL.createObjectURL(zip.generate({type:"blob"}));

This causes the following error:

Uncaught TypeError: Object #<HTMLImageElement> has no method 'replace'

I also tried this:

var zip = new JSZip();
zip.file("image.png", canvas.toDataURL(), {base64: true});
var content = zip.generate();
var blobLink = document.getElementById('blob');
blobLink.download = "image.zip";
blobLink.href = window.URL.createObjectURL(zip.generate({type:"blob"}));

That appears to work, but then the image in the zip is not valid. What can I do to save the image properly?

like image 402
Fibericon Avatar asked Mar 08 '13 05:03

Fibericon


People also ask

How do I export a canvas image?

If you wish to make the user download the file as it is saved you can do the following: var canvas = document. getElementById("mycanvas"); var image = canvas. toDataURL("image/png").

How do I download a canvas as an image?

Here is an example, where clicking the button downloads the canvas as an image: Let's look at how this works. In the example above, we've created a canvas image and a button you can click to download it. This button uses toDataURL () to convert our canvas to an image URL data string.

What are HTML Canvas canvas?

HTML canvases can be used for a wide variety of applications such as drawing images, , animation and much more. A particularly useful feature that you can make use of in Javascript is the ability to capture a canvas as an image (formatted to your choice) and allow users to download this image all in one click.

How to extract the media files from a CANVAS app?

To extract the media files (images, videos, audio) from a canvas app, we can save the app as msapp file, rename the file with a ZIP extension, uncompress the file, and locate the embedded media in the "Assets" folder.


1 Answers

You're generating a data uri, which has schema, mime-type etc before the actual base64 data data:[<MIME-type>][;charset=<encoding>][;base64],<data>. You'll have to remove all the content before the data then use it.

zip.file("image.png", savable.src.substr(savable.src.indexOf(',')+1), {base64: true});
like image 142
Musa Avatar answered Oct 06 '22 00:10

Musa