JSFiddle - React, Tailwind, and code Playground

by farhatdz

HTML

<input type="file" accept="image/*" onchange="preview(this.files[0])"/>
<br/>
<img id="img"/>

<canvas id="canvas" ></canvas>

JavaScript

function downloadImage(imgNode, name = 'fileName', format = 'png') {
  const canvas  = document.createElement('canvas');
  canvas.width  = imgNode.width;
  canvas.height = imgNode.height;

  const context  = canvas.getContext('2d');
  context.filter = getComputedStyle(imgNode).filter; // Add the image filter to the canvas
  imgNode.setAttribute('crossOrigin', 'anonymous');

  context.drawImage(imgNode, 0, 0, canvas.width, canvas.height);
  const url = canvas.toDataURL(`image/${format}`);

  const anchor    = document.createElement('a');
  anchor.href     = url;
  anchor.download = `${name}.${format}`;
  document.body.appendChild(anchor);
  anchor.click();
}

function preview(file) {
  if (file) {
    var reader = new FileReader()
    reader.readAsDataURL(file);
    reader.onloadend = function () {
      var img = new Image();
      img.src = reader.result;
      img.style.filter = "grayscale(100%)"; // Apply the CSS filter on the image
      document.body.appendChild(img); // Display image
      img.onload = function() {
        downloadImage(img); // Download image
        img.onload = null; // Prevent onload function called twice
      };
    }
  }
}