如何在应用CSS过滤器的情况下保存图像 [英] How to save an image with CSS filter applied

查看:95
本文介绍了如何在应用CSS过滤器的情况下保存图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何将CSS过滤器应用于图像,然后将图像保存到磁盘.

I am wondering how I can apply a CSS filter to an image and then save the image to disk.

例如,我有一个图像标签,可以通过CSS施加棕褐色效果

For example, I have an image tag, I can apply a sepia effect via CSS

img.sepia{
  filter: sepia(20%);
}

并将该类应用于HTML中的图片标签

And apply the class to an image tag in the HTML

<img src="img.png" class="sepia" />

如何在应用滤镜的情况下保存该图像?

How can I save that image with the filter applied?

推荐答案

您可以将图像写入canvas元素,在javascript中设置所需的过滤器,然后下载.所以会是这样的

You could write the image to a canvas element, set the filter you want in javascript and then download that. So it would be something like this

var canvas = document.getElementById('image');
var ctx = canvas.getContext('2d');
ctx.filter = "sepia(20%)";
var img = document.getElementById("dataimage");
ctx.drawImage(img,0,0, canvas.width, canvas.height);

var downloadFile = document.getElementById('download');
downloadFile.addEventListener('click', download, false);


function download() {
   var dt = canvas.toDataURL('image/jpeg');
   this.href = dt;
};

img{
  width:400px;
  height:400px;
}

<img src="" id="dataimage" />
<canvas id="image" width="400px" height="400px"></canvas>
<a id="download">Download image</a>

这篇关于如何在应用CSS过滤器的情况下保存图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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