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 learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Special FX, Noise >>
Previous chapter: Special FX, Greyscale
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.