Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an image with CSS filter applied

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

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

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

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?

like image 704
Rahul Avatar asked Oct 04 '16 14:10

Rahul


People also ask

Can you style an image in CSS?

Styling images in CSS works exactly the same way as styling any element using the Box Model of padding, borders, and margins for the content. There are many ways to set style in images which are listed below: Thumbnail images. Rounded images.


1 Answers

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>
like image 93
Teia Jamese Atkins Avatar answered Sep 16 '22 19:09

Teia Jamese Atkins