How to apply sepia tone to an image in html5 canvas?

Unlike converting an image to grayscale where same values are used for all the color channels in a pixel, applying sepia tone is little different.

In grayscale, we used different shades of gray, whereas in sepia, a distinct brown-gray color is used. The process is similar but the formula which is used to calculate the values of red, blue, and green channels of a pixel is different.

 

One of the commonly used formulae for applying sepia tone to a color(RGB) image is shown below. The multipliers can be changed a little to get the desired effect.

sepia tone formula(algorithm)

 

Note: To know more about manipulating pixels in canvas using JavaScript, you can visit the link shown below.

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

 

Using the formula in JavaScript:

var imageData = context.getImageData(imageX, imageY, image.width, image.height);
var dataArray = imageData.data;

for(var i = 0; i < dataArray.length; i += 4)
{
    var red = dataArray[i];
    var green = dataArray[i + 1];
    var blue = dataArray[i + 2];
    var alpha = dataArray[i + 3];

    var outRed = (red * .393) + (green *.769) + (blue * .189); // calculate value for red channel in pixel
    var outGreen = (red * .349) + (green *.686) + (blue * .168);
    var outBlue = (red * .272) + (green *.534) + (blue * .131);

    dataArray[i] = outRed < 255 ? outRed : 255; // check if the value is less than 255, if more set it to 255
    dataArray[i + 1] = outGreen < 255 ? outGreen : 255;
    dataArray[i + 2] = outBlue < 255 ? outBlue : 255
    dataArray[i + 3] = alpha;
}
        
context.putImageData(imageData, imageX, imageY);

 

Below, you can see the original image:

original flowers photo

 

The image after sepia tone has been applied:

sepia tone applied to the flowers photo

 

Related:

Converting an image to grayscale in html5 canvas.

Invert image colors (create negative) in html5 canvas using JavaScript.

Attachment: 
McAfee APAC


You might want to contribute to Qoncious.com:




Latest Videos