Image Colorising In PHP

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.

/**
 * Colorise an image.
 *
 * @param resource $image
 *   The image resource.
 * @param int $r
 *   The red part of the color (0 to 255).
 * @param int $g
*   The green part of the color (0 to 255).
 * @param int $b
*   The blue part of the color (0 to 255).
 * @param int $percent
 *   The percentage of colorisation that should occur.
 */
function imagecolorise(&$image, $r, $g, $b, $percent) {
  // Ensure the percentage is restricted to a given value.
  if ($percent < 0) {
    $percent = 0;
  } elseif ($percent > 100) {
    $percent = 100;
  }

  // Get the image's width.
  $imageWidth = imagesx($image);

  // Get the image's height.
  $imageHeight = imagesy($image);

  // Create the layover image.
  $layover = imagecreate($imageWidth, $imageHeight);

  // Allocate the color on this image.
  $color = imagecolorallocate($layover, $r, $g, $b);

  // Merge the layover image on top of the other image.
  imagecopymerge($image, $layover, 0, 0, 0, 0, $imageWidth, $imageHeight, $percent);

  // Destroy the layover image.
  imagedestroy($layover);
}

We can use this function in the following way.

// Load an image.
$image = imagecreatefromjpeg('my_image.jpeg');

// Colorise the image with a blue color at 75% saturation.
imagecolorise($image, 10, 10, 200, 75);

// Save the new image.
imagepng($image, 'colorised.png');

// Destroy the loaded image.
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.
CAPTCHA
1 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.