Skip to content Skip to sidebar Skip to footer

Save Images After Using Css Filter

I'm building a new website that will let users apply filters to images (just like Instagram). I will use -webkit-filter for that. The user must be able to save the filtered image.

Solution 1:

You can't save images directly, but you can render them in Canvas, then save from there.

See: Save HTML5 canvas with images as an image

Solution 2:

There is no direct/straight forward method to export an image with CSS Filter. Follow the below steps for Saving/Exporting an Image with -webkit-filter applied on it: 1. Render the image to a canvas:

var canvas = document.createElement('canvas');
canvas.id="canvasPhoto";
canvas.width = imageContaainer.width;
canvas.height = imageContaainer.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(imageContaainer, 0, 0, canvas.width, canvas.height);
  1. Get the ImageData from canvas and apply the filter. Eg: I will apply grayscale filter to the ImageData below:

    functiongrayscale(ctx) {
    var pixels = ctx.getImageData(0,0,canvas.width, canvas.height);
    var d = pixels.data;
    for (var i=0; i<d.length; i+=4) {
        var r = d[i];
        var g = d[i+1];
        var b = d[i+2];
        var v = 0.2126*r + 0.7152*g + 0.0722*b;
        d[i] = d[i+1] = d[i+2] = v
    }
    context.putImageData(pixels, 0, 0);
    }
    
  2. Add an event and use the below code to trigger download

    functiondownload(canvas) {
       var data = canvas.toDataURL("image/png");
       if (!window.open(data)) 
       {
           document.location.href = data;
       }
    }
    

Post a Comment for "Save Images After Using Css Filter"