I am trying to convert an HTML5 canvas to an image. This is what I got so far:
var tmp_canvas = document.getElementById('canvas');
var dataURL = tmp_canvas.toDataURL("image/png");
$('#thumbnail_list').append($('<img/>', { src : dataURL }).addClass('image'));
but the problem is that I get this code:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAYAAADtt+XCAAAgAElEQVR4nNS6Z1xVaZbvv/c+CVOZc6mYEMlJMZRizgljGRARs6AgOSMGQATBSM5ZyTkoOQkSzJWrp3t6etLt6Z7pmf/c++L7f3EOiBZW2dM9dz73xfdzztl7n3Oe/Txrrd9a69mCTC4gkwvIZAKSTECUBARRQBA+jii+46f.......class="image">
I want a normal image path that the user can download!
Any help?
First, add the generated data URL to the
hrefattribute of an<a>tag.However on some browsers, this alone will not trigger a download. Instead it will open the linked image in a new page.
Download dialog for a base64 image:
Based on above example, convert the MIME type of the data URL to this:
By telling the browser that the data are
application/octet-stream, it will ask you to save it on your hard-disk.Specifying a filename:
As Adi said in the comments below, there is no standard way to define a filename using this method. But, there are two approaches which might work in some browsers.
A) The
downloadattribute introduced by Google CromeB) Defining HTTP headers within the data URL
headers=Content-Disposition: attachment; filename=image.pngThis worked at least in some older versions of Opera.
Here is some discussion about this.
Looking into the Bug/Feature-Tracking systems of the major browsers shows that defining a filename is quite a big wish of the community. Maybe we will see a cross-browser compatible solution in near future! 😉
Save RAM and CPU ressources:
If you don’t want to bloat the RAM of your visitor’s browser, you can also generate the data URL dynamically:
This way, your canvas may still be shown as an image file by your browser.
If you want to increase the probability to open a download dialog, you should extend the function above, so that it does the replacement as shown above:
Last, add the HTTP header to make extra sure that most browsers offer a valid filename to you! 😉
FULL EXAMPLE: