Image Colorising In PHP

14th January 2019

Colorising images is fairly simple to accomplish, especially using PHP's GD library. All we need to do is load an image, create a blank image of the same size in a particular color and then merge the two images together.

In fact, we can do this entirely with the imagecopymerge() function, but creating a function to wrap all of this makes sense as well.

The following function takes an image resource (as created by imagecreatefrompng()), the red, green, and blue values of the color, and the percentage to overlay the color on top of the image. The percentage can be set to 0 for no effect and 100 to fully replace the image with the given color.

  1. /**
  2.  * Colorise an image.
  3.  *
  4.  * @param resource $image
  5.  * The image resource.
  6.  * @param int $r
  7.  * The red part of the color (0 to 255).
  8.  * @param int $g
  9. * The green part of the color (0 to 255).
  10.  * @param int $b
  11. * The blue part of the color (0 to 255).
  12.  * @param int $percent
  13.  * The percentage of colorisation that should occur.
  14.  */
  15. function imagecolorise(&$image, $r, $g, $b, $percent) {
  16. // Ensure the percentage is restricted to a given value.
  17. if ($percent < 0) {
  18. $percent = 0;
  19. } elseif ($percent > 100) {
  20. $percent = 100;
  21. }
  22.  
  23. // Get the image's width.
  24. $imageWidth = imagesx($image);
  25.  
  26. // Get the image's height.
  27. $imageHeight = imagesy($image);
  28.  
  29. // Create the layover image.
  30. $layover = imagecreate($imageWidth, $imageHeight);
  31.  
  32. // Allocate the color on this image.
  33. $color = imagecolorallocate($layover, $r, $g, $b);
  34.  
  35. // Merge the layover image on top of the other image.
  36. imagecopymerge($image, $layover, 0, 0, 0, 0, $imageWidth, $imageHeight, $percent);
  37.  
  38. // Destroy the layover image.
  39. imagedestroy($layover);
  40. }

We can use this function in the following way.

  1. // Load an image.
  2. $image = imagecreatefromjpeg('my_image.jpeg');
  3.  
  4. // Colorise the image with a blue color at 75% saturation.
  5. imagecolorise($image, 10, 10, 200, 75);
  6.  
  7. // Save the new image.
  8. imagepng($image, 'colorised.png');
  9.  
  10. // Destroy the loaded image.
  11. imagedestroy($image);

Taking the following image as an example.

Hammer and nails image

TRΛVELER .

If we process this through the above code we can apply a very deep blue to the image so that it looks like this.

Colorised hammer and nail

Using this function it is possible to quickly apply a mask to an image to help it blend in the background of a web page. It is also possible to use the imagecopymerge() function to create a watermark for an image by layering one image on top of another.

Add new comment

The content of this field is kept private and will not be shown publicly.