11

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?

Jason Yost
  • 4,807
  • 7
  • 42
  • 65
Rahul
  • 929
  • 2
  • 8
  • 17
  • [Screen grab](https://support.microsoft.com/en-us/help/13776/windows-use-snipping-tool-to-capture-screenshots) – adeneo Oct 04 '16 at 14:28
  • You can always take screenshots from screen if you are looking for your own use. – poush Oct 04 '16 at 14:29
  • 1
    Nope, i basically wants to use it for my website. so if i upload a photo to website so i can apply filter on it by css and then save it to my gallery. – Rahul Oct 04 '16 at 15:29
  • You cannot access the file system from JavaScript running in a browser. – rockerest Oct 04 '16 at 15:49
  • Yes exactly you cannot save the images ... but, give user a prompt to save the image .. Use https://html2canvas.hertzen.com/ to take screenshot of any size from the browser page. . – Atul Sharma Oct 04 '16 at 18:26

2 Answers2

8

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>
CodeIt
  • 3,492
  • 3
  • 26
  • 37
  • Okay. thanks for the idea. i will learn canvas now. to solve this issue. but that download button didn't worked for me.. :) – Rahul Oct 05 '16 at 16:53
0

Check the browser compatibility before you choose the canvas method: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter

It's not supported on most mobile browsers.

I use an image service like Cloudinary.

slotdp02
  • 438
  • 1
  • 6
  • 15