Motyar

@motyar

Freelance Web Developer

Static Web Hosting, made easy

Aug 27, 2010

Convert Color Images to Grayscale with Canvas and Jquery

I like to make things easier and simpler. Now here in this post i am sharing "How to convert color images to grayscale with canvas and Javascript". This script can cut a number of images when using GrayScale hover effect. you can use this script in your Online Image Grayscale Converter tool or Software.

Idea

As you know, color image consists of 3 color components: red, green and blue. To convert a color to grayscale we just need to calculate the average for all three color components.
This script we are using canvas, becuase with canvas we can go through image’s each pixel and can replace the color values with an average (grayscale) value.
You can download the generated gray-scale images with php, Or by right clicking them.

Code


$(document).ready(function(){
        $('.gray').click(function(){
    this.src =  grayscale(this.src);  
        });
});

function grayscale(img)
{        
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
        
    var imgObj = new Image();
    imgObj.src = img;
       
    canvas.width = imgObj.width;
    canvas.height = imgObj.height; 

    ctx.drawImage(imgObj, 0, 0); 
  
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
        
    for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
               var i = (y * 4) * imgPixels.width + x * 4;
               var avg = (imgPixels.data[i] + 
                          imgPixels.data[i + 1] + 
                          imgPixels.data[i + 2]
                          ) / 3;
               imgPixels.data[i] = avg; 
               imgPixels.data[i + 1] = avg; 
               imgPixels.data[i + 2] = avg;
            }
    }
   
        ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        return canvas.toDataURL();
    }

HTML
<img src="motyar.png" class="gray"/>

DEMO

You can see the working demo here. ( This example only works on browsers that supports HTML 5 Canvas )

Labels: , , ,




By :