JavaScript:将背景图像保存到用户的磁盘

时间:2018-04-24 18:53:03

标签: javascript html

我有这个HTML元素:

<div style='background-image: url("data:image/png; base64, ENCODEDPNGBYTEDATA")' />

如何直接从background-image属性中提取图像并显示一个保存文件对话框,以允许用户将图像文件保存在他的磁盘上?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

// Get the image id, style and the url from it
var img = document.getElementById('testdiv'),
  style = img.currentStyle || window.getComputedStyle(img, false),
  bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");

// Display the url to the user
console.log('Image URL: ' + bi);

<div id="testdiv" style="background-image:url('http://placehold.it/200x200');"></div>

在这种情况下,你从你的imagen获得网址,你可以添加一个链接以下载你的图像 示例

<a href="/path/to/image.png" download="AwesomeImage.png">
相关问题