3

I have a transparent PNG image. The transparent areas need to remain completely transparent, but the other areas need tinting with a particular hue.

What's the best way to do this using GD?

Cheers,
James

James Hall
  • 7,507
  • 2
  • 22
  • 15
  • Be sure to check out the solution for a way to tint white areas, by using negate: https://stackoverflow.com/a/12179050/1164342 – Hayden Thring Dec 27 '18 at 09:48

2 Answers2

7

The above solution didn't work for me.

You are filling alpha region here with red; that I believe is not the objective. Objective is to tint the rest of the image and leave the alpha unchanged. (Also, wrong use of function imagecolorallocate, you should use imagecolorallocatealpha.)

I managed to use imagefilter and colorize as follows:

imagefilter($image, IMG_FILTER_COLORIZE, 0, 255, 0, 30);

to apply tinting.

Community
  • 1
  • 1
nunespascal
  • 17,584
  • 2
  • 43
  • 46
2

The GD library does support alpha transparency so this should not be a problem. Here's how I'd put it together - you may need to tweak this, but the gist of it should be there.

Red/green/blue are 0-255. Alpha is 0-127 (127 being fully transparent). This code should apply a 50% red tint to the image "original.png" and output as "output.png".

<?php

$red = 255;
$green = 0;
$blue = 0;
$alpha = 63

$src_img = imagecreatefrompng("original.png");
$tint_img = imagecreatetruecolor(imagesx($im_src), imagesy($im_src));
$tintcolor = imagecolorallocate($tint_img, $red, $green, $blue, $alpha);
imagefill($tint_img, 0, 0, $tintcolor);
imagecopymerge($tint_img, $src_img, 0, 0, 0, 0, imagesx($im_src), imagesy($img_src), 100);
imagepng("output.png");

?>
pix0r
  • 31,139
  • 18
  • 86
  • 102