Save images after using CSS filter

后端 未结 2 1589
臣服心动
臣服心动 2020-12-18 16:45

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

相关标签:
2条回答
  • 2020-12-18 17:11

    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

    0 讨论(0)
  • 2020-12-18 17:18

    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:

      function grayscale(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

      function download(canvas) {
         var data = canvas.toDataURL("image/png");
         if (!window.open(data)) 
         {
             document.location.href = data;
         }
      }
      
    0 讨论(0)
提交回复
热议问题