5.8 Pixel Manipulation 147
(r+g+b)/3.0
);
return [val,val,val,a];
};
With grayLuminosity(), we are using the second formula in Figure 5.29, replac-
ing the RGB component of each pixel with the new calculated value. In this and
all following calculations, we must not forget that RGBA values can only be inte-
gers; the JavaScript method parseInt() makes sure of it.
The algorithm for sepiaTone() was taken from an article by Zach Smith, titled
How do I ... convert images to grayscale and sepia tone using C#? (see the short-
ened web link http://bit.ly/a2nxI6)::)
var sepiaTone = function(r,g,b,a) {
var rS = (r0.393)+(g0.769)+(b0.189);
var gS = (r0.349)+(g0.686)+(b0.168);
var bS = (r0.272)+(g0.534)+(b*0.131);
return [
(rS>255)? 255 : parseInt(rS),
(gS>255)? 255 : parseInt(gS),
(bS>255)? 255 : parseInt(bS),
a
];
};
Adding up the multiplied components can lead to values larger than 255 in each
of the three calculations; in this case, 255 is inserted as a new value.
Inverting colors is very easy with the filter invertColor(): You simple deduct
each RGB component from 255:
var invertColor = function(r,g,b,a) {
return [
(255-r),
(255-g),
(255-b),
a
];
};
The filter swapChannels() modifies the sequence of the color channels. We first
need to define the desired order as the fourth parameter in an array, where 0 is
red, 1 is green, 2 is blue, and 3 is the alpha channel. To swap channels, we use the
array rgba with the corresponding starting values and then return it in the new
order. So changing from RGBA to BRGA, as in our example, can be achieved via
order=[2, 0, 1, 3]: