Convert Image to Grayscale

In this example below you will see how to do a Convert Image to Grayscale with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by dalir, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright dalir ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Convert Image to Grayscale </title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <script src="https://www.dukelearntoprogram.com/course1/common/js/image/SimpleImage.js">
</script>
<h1>Upload image</h1>
<canvas id="can1"></canvas>
<canvas id="can2"></canvas>
<p>
  Foreground: <input type="file" id="finput1" multiple="false" accept="image/*" onchange="uploadMe()">
    Background: <input type="file" id="finput2" multiple="false" accept="image/*" onchange="uploadMe()">
  <input type="button" id="" value="Make Gray" onclick="makeGray()">
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/dalir/convert-image-to-grayscale-QGvVWq */
h1 {
  color: darkred;
}
canvas {
  width: 320px;
  height: auto;
  border: 2px dotted #777;
}

/*Downloaded from https://www.codeseek.co/dalir/convert-image-to-grayscale-QGvVWq */
var image1;
var image2;

function uploadMe(){
  var inputfile1 = document.getElementById("finput1");
  image1 = new SimpleImage(inputfile1);
   var inputfile2 = document.getElementById("finput2");
  image2 = new SimpleImage(inputfile2);
  var canvas1 = document.getElementById("can1");
  var canvas2 = document.getElementById("can2");
  image1.drawTo(canvas1);
  image2.drawTo(canvas2);
}

function makeGray(){
  for (var pixel of image2.values()) {
    var avr =(pixel.getRed()+pixel.getGreen()+pixel.getBlue())/3;
  
  pixel.setRed(avr);
  pixel.setGreen(avr);
  pixel.setBlue(avr);
  }
  var canvas2 = document.getElementById("can2");
  image2.drawTo(canvas2);
  }

Comments