Html 将画布另存为 jpg 到桌面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17397319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save canvas as jpg to desktop
提问by Rajkamal
I am trying to save an image (JPEG) to the desktop from an HTML5canvas. I can open in a new window window.open(canvas.toDataURL('png'), "");
, but how can I save it to the desktop? Thanks.
我正在尝试从 HTML5canvas 将图像 (JPEG) 保存到桌面。我可以在新窗口中打开window.open(canvas.toDataURL('png'), "");
,但如何将其保存到桌面?谢谢。
回答by
Download attribute
下载属性
There is a new download attributein HTML5 that allow you to specify a file-name for links.
HTML5 中有一个新的下载属性,允许您为链接指定文件名。
I made this for saving canvas. It has a link ("Download as image") -
我做这个是为了节省画布。它有一个链接(“下载为图片”)-
<a id="downloadLnk" download="YourFileName.jpg">Download as image</a>
And the function:
和功能:
function download() {
var dt = canvas.toDataURL('image/jpeg');
this.href = dt;
};
downloadLnk.addEventListener('click', download, false);
You can even change the file-name dynamically by setting the attribute downloadLnk.download = 'myFilename.jpg'
.
您甚至可以通过设置属性来动态更改文件名downloadLnk.download = 'myFilename.jpg'
。
Demofrom the archives.
来自档案的演示。
回答by Ashish Chopra
Check this if it helps, A jsfiddle implemented for same requirement. http://jsfiddle.net/5whKM/
如果有帮助,请检查它,针对相同要求实现的 jsfiddle。 http://jsfiddle.net/5whKM/
<img src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7"/>
<script>
var img = document.images[0];
img.onclick = function() {
var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
location.href = url;
};
</script>
回答by Mzn
What you should do in this case, is to send the user window.location=canvas.toDataURL('png')
to the location of the file you want them to 'download'. So your solution of opening a new windows is what you should do, and is what 'downloading' is.
在这种情况下,您应该做的是将用户发送window.location=canvas.toDataURL('png')
到您希望他们“下载”的文件所在的位置。因此,您打开新窗口的解决方案是您应该做的,这就是“下载”。
For example, if you want them to save an EXE for a file, you just let them click on an anchor , and the browser handles requesting the file and downloading it. You can also do that with JavaScript, but it's a security and user-experience problem to just pop SaveAs for the users.
例如,如果您希望他们为文件保存 EXE,您只需让他们点击一个锚点,浏览器就会处理请求文件并下载它。您也可以使用 JavaScript 执行此操作,但仅为用户弹出 SaveAs 是一个安全和用户体验问题。
Also check this out: Browser/HTML Force download of image from src="data:image/jpeg;base64..."
另请查看:Browser/HTML Force download of image from src="data:image/jpeg;base64..."