How to save a png from javascript variable How to save a png from javascript variable javascript javascript

How to save a png from javascript variable


I know this question is 2 years old, but hopefully people will see this update.

You can prompt the user to save an image in a base64 string (and also set the filename), without asking the user to do a right click

var download = document.createElement('a');download.href = dataURI;download.download = filename;download.click();

Example:

var download = document.createElement('a');download.href = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';download.download = 'reddot.png';download.click();

In order to trigger a click event using Firefox, you need to do what it is explained in this SO answer. Basically:

function fireEvent(obj,evt){  var fireOnThis = obj;  if(document.createEvent ) {    var evObj = document.createEvent('MouseEvents');    evObj.initEvent( evt, true, false );    fireOnThis.dispatchEvent( evObj );  } else if( document.createEventObject ) {    var evObj = document.createEventObject();    fireOnThis.fireEvent( 'on' + evt, evObj );  }}fireEvent(download, 'click')

As of 20/03/2013, the only browser that fully supports the download attribute is Chrome. Check the compatibility table here


... without asking to the visitor anyhing ... Is it possible?

No, that would have been a security hole. If it was possible, one would be able to write malware to the enduser's disk unaskingly. Your best bet may be a (signed) Java Applet. True, it costs a bit of $$$ to get it signed (so that it doesn't pop security warnings), but it is able to write data to enduser's disk without its permission.


I am surprised nobody here mentioned using HTML5 blobs together with a couple of nice libraries.

You first need https://github.com/eligrey/FileSaver.js/ and https://github.com/blueimp/JavaScript-Canvas-to-Blob.

Then you can load the image into a canvas

base_image = new Image();base_image.src ='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

the canvas into a blob

var canvas = document.getElementById('YourCanvas');context = canvas.getContext('2d');// Draw image withincontext.drawImage(base_image, 0,0);

and finally save it

x_canvas.toBlob(function(blob) {saveAs(blob, "screenshot.png");}, "image/png");

FF is not fully supported but at least you get a separate page with the image.

Check this out: http://jsfiddle.net/khhmm/9/

EDIT: this is not compatible with Safari / Mac.