将图像保存到硬盘 [英] Save image to hard drive

查看:56
本文介绍了将图像保存到硬盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用图像将图片加载到画布上.
然后,我希望我的用户可以选择将图像保存到他们的硬盘驱动器.

I use an Image to load a picture onto a canvas.
I would then like to be able to my User the option to save the image to their hard drive.

如果我使用Ajax并从服务器中检索,我已经进行了搜索,并且有很多方法可以做到这一点.

I have searched around and there are plenty of ways to do this IF I use Ajax and retrieve from my server.

是否可以避免通过服务器访问图像并通过图像控件或画布控件将其直接保存到硬盘中

Is there a way to avoid any trips to my server and to save directly onto my hard drive either via the image control or the canvas control

推荐答案

实际上,您可以使用步骤将是:

  1. 使用画布创建图像
  2. 使用 download 属性
  3. 附加不可见的链接
  4. 触发链接 onclick 事件
  5. 删除隐藏的链接

类似这样的东西:

myCanvas = document.getElementById("myCanvas");

$("body").append("<a id='hiddenLink' href='" + myCanvas.toDataURL() + "' style='display:none;' download>Download Pic</a>");
$("#hiddenLink")[0].click();
$("#hiddenLink").remove();

您可以在这里看到它的运行情况: http://jsfiddle.net/wLd4yf7k/

You can see it working here: http://jsfiddle.net/wLd4yf7k/

一个问题:并非所有浏览器都支持它: http://caniuse.com/#feat=download

One issue: not all the browsers will support it: http://caniuse.com/#feat=download

在这里,您有一个仅使用JavaScript(没有jQuery)的解决方案,因为我看到您没有在问题中添加jQuery标记:

And here you have a solution using exclusively JavaScript (no jQuery), as I see that you didn't add a jQuery tag to the question:

myCanvas = document.getElementById("myCanvas");

a = document.createElement("a");
a.href = myCanvas.toDataURL();
a.download = "download";
a.click();

您可以看到它在提琴上起作用: http://jsfiddle.net/wLd4yf7k/1/

You can see it working on the fiddle: http://jsfiddle.net/wLd4yf7k/1/

这篇关于将图像保存到硬盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆