Changing saturation of an image in html5 canvas using JavaScript.

In simple words, the saturation of a color pixel means the amount of color in that pixel. If saturation is more the image looks more colorful and intense and if it is less the image looks washed out and lacking in color.

To know more about saturation, visit this link.

 

The original image on which different saturation levels will be applied:

spring garden original image

 

Algorithm:

algorithm to change image saturation

 

How to achieve this using the canvas api?

JavaScript code snippet: You can download the attachment containing the code and image at the end of this page

var imageData = context.getImageData(imageX, imageY, image.width, image.height);
var dA = imageData.data; // raw pixel data in array

var sv = 2; // saturation value. 0 = grayscale, 1 = original

var luR = 0.3086; // constant to determine luminance of red. Similarly, for green and blue
var luG = 0.6094;
var luB = 0.0820;

var az = (1 - sv)*luR + sv;
var bz = (1 - sv)*luG;
var cz = (1 - sv)*luB;
var dz = (1 - sv)*luR;
var ez = (1 - sv)*luG + sv;
var fz = (1 - sv)*luB;
var gz = (1 - sv)*luR;
var hz = (1 - sv)*luG;
var iz = (1 - sv)*luB + sv;

for(var i = 0; i < dA.length; i += 4)
{
    var red = dA[i]; // Extract original red color [0 to 255]. Similarly for green and blue below
    var green = dA[i + 1];
    var blue = dA[i + 2];

    var saturatedRed = (az*red + bz*green + cz*blue);
    var saturatedGreen = (dz*red + ez*green + fz*blue);
    var saturateddBlue = (gz*red + hz*green + iz*blue);

    dA[i] = saturatedRed;
    dA[i + 1] = saturatedGreen;
    dA[i + 2] = saturateddBlue;
}
        
context.putImageData(imageData, imageX, imageY);

 

Saturation level 0 (grayscale):

saturation level zero

 

Saturation level 2 makes the image more colorful:

saturation level two

 

Note: You can change the saturation level to achieve the desired output. Value 0 converts the image to grascale, while 1 has no effect.

 

Related:

How to load an image into html5 canvas and do pixel manipulation?




You might want to contribute to Qoncious.com:




Latest Videos