Duotone Image

<?php

/**
 * duotone_image
 *
 * Change an image into a tinted grayscale.
 *
 * @version 0.5
 * @author Contributors at eXorithm
 * @link /algorithm/view/duotone_image Listing at eXorithm
 * @link /algorithm/history/duotone_image History at eXorithm
 * @license /home/show/license
 *
 * @param resource $image (GD image) The image to duotone.
 * @param number $rplus Red value to increase or decrease.
 * @param number $gplus Green value to increase or decrease.
 * @param number $bplus Blue value to increase or decrease.
 * @param bool $pcnt If checked, the values for rplus, gplus and bplus will be treated as percentages.
 * @return resource GD image
 */
function duotone_image($image=null,$rplus=0,$gplus=0,$bplus=60,$pcnt=false)
{
	// Adapted from http://www.tuxradar.com/practicalphp/11/2/21
	
	$imagex = imagesx($image);
	$imagey = imagesy($image);
	
	$image2 = imagecreatetruecolor($imagex, $imagey);
	imagesavealpha($image2, true);
	imagealphablending($image2, false);
	
	for ($x = 0; $x <$imagex; ++$x) {
		for ($y = 0; $y <$imagey; ++$y) {
			$rgb = imagecolorat($image, $x, $y);
			$color = imagecolorsforindex($image, $rgb);
			$grey = floor(($color['red']+$color['green']+$color['blue'])/3);
			if ($pcnt) {
				$red = $grey + $grey*($rplus/150);
				$green = $grey + $grey*($gplus/150);
				$blue = $grey + $grey*($bplus/150);
			} else {
				$red = $grey + $rplus;
				$green = $grey + $gplus;
				$blue = $grey + $bplus;
			}
			
			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 = imagecolorallocatealpha($image2, $red,$green,$blue,$color['alpha']);
			imagesetpixel ($image2, $x, $y, $newcol);
		}
	}
	
	return $image2;
}

?>