11.2.21 Special FX, DuotoneThis is NOT the latest copy of this book; click here for the latest version.
Once you have mastered the greyscale effect, you are 95% of the way there with duotone. This effect is essentially a tinted greyscale, which means that we average the red, green, and blue values then add or subtract a little from each of them to get a particular tint. In order to handle the tint values, our function needs to accept four parameters: the image, a red amount, green amount, and blue amount. There is one additional check to be made for each colour, and that is that it is not over 255 - the maximum value for a single colour. Here is the new function:
function duotone (&$image, $rplus, $gplus, $bplus) {
$imagex = imagesx($image);
$imagey = imagesy($image);
for ($x = 0; $x <$imagex; ++$x) {
for ($y = 0; $y <$imagey; ++$y) {
$rgb = imagecolorat($image, $x, $y);
$red = ($rgb >> 16) & 0xFF;
$green = ($rgb >> 8) & 0xFF;
$blue = $rgb & 0xFF;
$red = (int)(($red+$green+$blue)/3);
$green = $red + $gplus;
$blue = $red + $bplus;
$red += $rplus;
if ($red > 255) $red = 255;
if ($green > 255) $green = 255;
if ($blue > 255) $blue = 255;
if ($red < 0) $red = 0;
if ($green < 0) $green = 0;
if ($blue < 0) $blue = 0;
$newcol = imagecolorallocate ($image, $red,$green,$blue);
imagesetpixel ($image, $x, $y, $newcol);
}
}
}
The first half of that is basically identical to our greyscale function, but note that the new function takes $rplus, $gplus, and $bplus to handle users passing in tinting information. Now, when the colours are average, the value is stored in $red. The $green variable is then set to the value of $red plus the $gplus, which is the green tint amount passed into the function. The same is done for blue, with $blue and $bplus.
Finally, the $red variable itself is changed to reflect the red tint amount, then a new colour is allocated based upon these three and the pixel is coloured in with imagesetpixel().

|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|