Tint Images with PHP

Penguin tinted 000099 Penguin tinted 006600 Penguin tinted 990099 Penguin tinted ff0000 Penguin tinted 008080 Penguin tinted c85028

Have you ever wanted to make an army of multicolored penguins? If so, you've come to the right place. This code works for quite a few more useful applications such as creating custom colored buttons and icons on the fly too. Basically, we're just going through the colors of a grayscale image and replacing each with an appropriately tinted new color.

PenguinTo start, we'll need to take our source image and turn it into a grayscale one. The IMG_FILTER_GRAYSCALE filter type of PHP's imagefilter function does this, but we recommend converting the image yourself in PhotoShop instead for best results. Also, we've found that the tinting function below works best on GIF images, so you should probably convert your starting image to that format if it's currently a JPEG or PNG. (Note: You can make slight edits to the functions below – using imagecreatefromjpeg instead of imagecreatefromgif, for example – and use other formats if you prefer.) The black and white penguin GIF on our left is the one that we'll be using in our example.

Our example includes opening up the GIF, converting it to blue, and then outputting it to the browser as a GIF. You could also save the image at this point using the content-disposition header instead if you'd like.

1.   $image_path = 'images/inkplant/code/penguin.gif';
2.   $new_hex = '000099';
3.   $img = image_convert_grays_to_color($image_path,$new_hex);
4.   header('Content-Type: image/gif');
5.   imagegif($img);
6.   imagedestroy($img);

Now, let's walk through what each of the functions are doing…

This first one, image_convert_grays_to_color, calls the other two and is the real core of this functionality. $image_path is your source image; it can be either a local path or a URL. $new_hex is the 6-digit hexadecimal color code of the tint you want to apply. (Make sure to remove the # from the front.

After opening the black and white image, it goes through, pixel by pixel and composes a list of all available colors. Those are then converted to the new tinted version. Finally, imagecolorset is used to convert all instances of the old color to the new one.

1.   function image_convert_grays_to_color($image_path,$new_hex) {
2.   	$img = @imagecreatefromgif($image_path);
3.   	if (!$img) { die('Could not open image: '.$image_path); }
4.   
5.   	$new_color = hex_to_rgb($new_hex);
6.   
7.   	$colors = image_get_all_colors($img);
8.   
9.   	$image_is_bw = true;
10.  	foreach ($colors as $key => $c) {
11.  		//check that color is gray or black
12.  		if (($c['red'] != $c['blue']) || ($c['blue'] != $c['green']) || ($c['green'] != $c['red'])) { $image_is_bw = false; break; }
13.  	}
14.  	if (!$image_is_bw) { //if image isn't black & white, convert it
15.  		imagefilter($img, IMG_FILTER_GRAYSCALE);
16.  		$colors = image_get_all_colors($img); //refresh the color palette
17.  	}
18.  
19.  	//remove white & lookup old color index
20.  	foreach ($colors as $key => $c) {
21.  		if (($c['red'] == 255) && ($c['green'] == 255) && ($c['blue'] == 255)) {
22.  			unset($colors[$key]);
23.  		} else {
24.  			$colors[$key]['index'] = imagecolorexact($img,$c['red'],$c['green'],$c['blue']);
25.  		}
26.  	}
27.  
28.  	foreach ($colors as $key => $c) {
29.  		//generate new color
30.  		foreach (array('red','green','blue') as $hue) {
31.  			$colors[$key]['new_'.$hue] = round($c[$hue] + $new_color[$hue] - ($c[$hue] / 3));
32.  			if ($colors[$key]['new_'.$hue] > 255) { $colors[$key]['new_'.$hue] = 255; }
33.  		}
34.  
35.  		//make sure it's light enough
36.  		$old_total = $c['red'] + $c['blue'] + $c['green'];
37.  		$new_total = $colors[$key]['new_red'] + $colors[$key]['new_blue'] + $colors[$key]['new_green'];
38.  		$i = 0;
39.  		while ($old_total > $new_total) {
40.  			$colors[$key]['diff'] = round(($old_total - $new_total) / 3);
41.  			//$colors[$key]['extra'] = 0;
42.  			foreach (array('red','green','blue') as $hue) {
43.  				$colors[$key]['new_'.$hue] = $colors[$key]['new_'.$hue] + $colors[$key]['diff'];
44.  				if ($colors[$key]['new_'.$hue] > 255) {
45.  					//$colors[$key]['extra'] = $colors[$key]['extra'] + ($colors[$key]['new_'.$hue] - 255);
46.  					$colors[$key]['new_'.$hue] = 255;
47.  				}
48.  			}
49.  			$new_total = $colors[$key]['new_red'] + $colors[$key]['new_blue'] + $colors[$key]['new_green'];
50.  			$i++;
51.  			if ($i > 5) { break; } //prevent too many loops
52.  		}
53.  		
54.  
55.  		//get hex codes (this isn't needed here, but it's useful for debugging or other applications)
56.  		$get_hex_codes = false;
57.  		if ($get_hex_codes) {
58.  			foreach (array('','new_') as $prefix) {
59.  				${$prefix.'hex'} = '';
60.  				foreach (array('red','green','blue') as $hue) {
61.  					$hue_hex = dechex($colors[$key][$prefix.$hue]);
62.  					if (strlen($hue_hex) < 2) { $hue_hex = '0'.$hue_hex; }
63.  					${$prefix.'hex'} .= $hue_hex;
64.  				}
65.  				$colors[$key][$prefix.'hex'] = '<span style="color:#'.${$prefix.'hex'}.';background-color:#'.${$prefix.'hex'}.';">'.${$prefix.'hex'}.'</span>';
66.  			}
67.  		}
68.  	}
69.  
70.  	//this is just here for debugging
71.  	if ($get_hex_codes) { echo '<pre>'.print_r($colors,true).'</pre>'; die(); }
72.  
73.  	//replace old colors with new
74.  	foreach ($colors as $key => $c) {
75.  		if ($c['index'] === false) { die('Error: No index could be found for color '.$key.'!'); }
76.  		imagecolorset($img,$c['index'],$c['new_red'],$c['new_green'],$c['new_blue']);
77.  	}
78.  
79.  	return $img;
80.  }

The image_get_all_colors function, below, does exactly what its name would suggest – it gets an array of all the colors used in an image. To do this, it goes through pixel by pixel and checks to see if that pixel's color has already been used. So, needless to say, if you were using this on a very large image, it would take a while.

1.   function image_get_all_colors($img) {
2.   	$colors = array();
3.   	$width = imagesx($img);
4.   	$height = imagesy($img);
5.   	$x = 0;
6.   	$y = 0;
7.   	while ($x < $width) {
8.   		while ($y < $height) {
9.   			$c = imagecolorat($img, $x, $y);
10.  			if (!array_key_exists($c,$colors)) { $colors[$c] = imagecolorsforindex($img,$c); }
11.  			$y++;
12.  		}
13.  		$y = 0;
14.  		$x++;
15.  	}
16.  	return $colors;
17.  }

The final function, hex_to_rgb, simply converts a hexadecimal color code into RGB 0-255 values so that we can do math on them to get our new tinted colors.

1.   function hex_to_rgb($hex) {
2.   	if (strlen($hex) != 6) { die('Error: Color hex code must be 6 characters for this function.'); }
3.   	return array(
4.   	  'hex'=>$hex,
5.   	  'red'=>hexdec(substr($hex,0,2)),
6.   	  'green'=>hexdec(substr($hex,2,2)),
7.   	  'blue'=>hexdec(substr($hex,4,2))
8.   	);
9.   }

PenguinAt the end of all this, you're left with a blue penguin. Or, in your case, something much more useful…

If you have questions or comments, please leave them below.


Comments

Loading…

This post was published on July 13th, 2014 by Robert James Reese in the following categories: Images and PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.