1

I am working with images, I want when someone upload image, then image should convert into black and white image. My following code is doing that for me, but when I right click on image and downloading it then it downloading image as coloured image. Looks like my code only showing image in black and white not converting it's quality. Is their any way by which I can give user converted black and white image?

JsFiddle: https://jsfiddle.net/4kcyqbz5/

Code:

<html>
<body>
<form>
<p><label for="file" style="cursor: pointer;"><b>Upload Image</b></label></p>
<p><input type="file" accept="image/*" name="image" id="file"  onchange="loadFile(event)"></p>

<p><img style="-webkit-filter: grayscale(100%); filter: grayscale(100%);" id="output" width="200" /></p><br>

</form>

<script>
var loadFile = function(event) {
    var image = document.getElementById('output');
    image.src = URL.createObjectURL(event.target.files[0]);
};
</script>
</body>
</html>
santosh
  • 742
  • 8
  • 19
  • You are not changing color of actual image, you are just add a style over the image, ofcourse it will be coloured image when you download it. Someone already asked the same question; https://stackoverflow.com/questions/28301340/changing-image-colour-through-javascript – Cem Jul 18 '20 at 08:42

1 Answers1

0

As Cem allready cleared up, you're not changing any image data. You're just using css to change the style of the image with a filter.

I prepared "simple" logic in the following snipped. You might see manipulating an image might take a bit of preparation with a canvas. You can find further details to image manipulation here: https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas.

EDIT: You can also download the manipulated image with changes from canvas.

let loadFile = function(event) {
    
  let image = document.getElementById("img");
  image.src = URL.createObjectURL(event.target.files[0]);  
};

document.getElementById("img").onload = (event => {
  let canvas = document.createElement("canvas");
  let context = canvas.getContext("2d");
  canvas.width = event.target.width;
  canvas.height = event.target.height;
  document.getElementById("output").appendChild(canvas);
  context.drawImage(event.target, 0, 0);
  let imageData = context.getImageData(0, 0, canvas.width, canvas.height);
  let data = imageData.data;
  for (var i = 0; i < data.length; i += 4) {
      var avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
      data[i]     = avg; // red
      data[i + 1] = avg; // green
      data[i + 2] = avg; // blue
    }
    context.putImageData(imageData, 0, 0);
});
<form>
<p><label for="file" style="cursor: pointer;"><b>Upload Image</b></label></p>
<p><input type="file" accept="image/*" name="image" id="file"  onchange="loadFile(event)"></p>

Changes Img in Canvas:
<div id="output"> </div>
Actual image:<br>
<img id="img" />

</form>
Pascal
  • 108
  • 1
  • 7