Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

image - How to save a png from javascript variable

I have an image encoded in base64 in a javascript variable : data:image/png;base64, base64 data

[EDIT] I need to save that file to disk without asking to the visitor to do a right click [/EDIT]

Is it possible ? How ?

Thanks in advance

Best regards

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...