javascript - Is it possible to save the <img> element as using js without sending a request for download?
漂亮男人
漂亮男人 2017-05-19 10:41:13
0
2
614
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test</title>
</head>
<body>

<img 
   src='https://sfault-avatar.b0.upaiyun.com/498/442/498442326-5810374d88a21_big64' 
   id='img' >

<button onclick="download()">下载</button>

<script>
/**
 * 是否存在某种途径,可以实现点击后,直接在浏览器端把图片保存到用户的电脑上?
 * ps: 我用尝试了一种方法,把img转成canvas,然后使用FileSaver.js能做到,
 * 但是,这个保存出来的图片,体积很大,存在性能问题。
 * 所以,我在想,能否直接把<img>元素的图片直接保存到用户的电脑上?
 * 一般的做法,都是点击按钮,发送一个请求到服务器下载到用户电脑上,
 * 我知道我这想法有点另类,但希望能讨论一下
 **/
function download(){
  var img = document.getElementById('img');
  //......

}
</script>
</body>
</html>
漂亮男人
漂亮男人

reply all(2)
我想大声告诉你

I was also thinking about canvas at first, but I saw that the questioner had already tried it. I haven't thought of anything else yet.

But for what you said about "the file size is too large", if you converted the image to base64 using canvas, it may be because you set the image format to png format, for example:

canvas.toDataURL('image/png')

If this is the case, then you can convert to jpeg format, and can control the conversion quality, so that it will be smaller when saved. For example:

canvas.toDataURL('image/jpeg',0.5);

I feel that if this is the case, there should be no problem in terms of size.

ps: I have used the download attribute of the a tag mentioned above, but it may be a bit problematic for the subject of the question.

1. Requests may still be required. If the download attribute can read images from the cache and save them, then there may be no need to request cached images (in fact, I don’t know if it has a mechanism to read cached images, maybe not at all). But for large images, even if they are loaded in the web page, downloading using the download attribute still needs to be downloaded from the server.

<a href="https://files.yande.re/image/eb619bf8aff0bd440ec724211fce245c/yande.re%20389825%20dress%20elf%20erect_nipples%20makita_yoshiharu%20no_bra%20nopan%20open_shirt%20pointy_ears%20see_through%20skirt_lift.jpg" download="a.jpg">xxxxx</a>
<br>
<img src="https://files.yande.re/image/eb619bf8aff0bd440ec724211fce245c/yande.re%20389825%20dress%20elf%20erect_nipples%20makita_yoshiharu%20no_bra%20nopan%20open_shirt%20pointy_ears%20see_through%20skirt_lift.jpg">

2. The download attribute in Firefox requires that the file in the href has the same origin as the domain name of the current web page, otherwise it will not be downloaded. However, judging from the situation of the subject, it should be from the same source, and this problem does not exist.

3.

phpcn_u1582

The download attribute of the a tag can be supported, but there are compatibility issues; better support generally needs to be completed by the server.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template