How can I tint transparent PNG files in PHP?
Asked Answered
S

2

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

Sacrarium answered 4/6, 2009 at 17:26 Comment(1)
Be sure to check out the solution for a way to tint white areas, by using negate: https://mcmap.net/q/1175694/-replace-a-color-with-another-in-an-image-with-phpSparrowgrass
D
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.

Ducktail answered 17/8, 2009 at 2:11 Comment(2)
Not sure why but it doesn't do anything. Tried various RGBA values to no avail. Tried IMG_FILTER_NEGATE and image turned totally blank !? Maybe my original image has an issue that imagefilter() can't handle?Mho
The PNG being white only, it turns into a 1-bit image so it can't be tinted with this method alone :( It needs to be converted to true oclor firstMho
E
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");

?>
Emelineemelita answered 4/6, 2009 at 17:42 Comment(1)
Documentation states imagecolorallocate does take only 4 arguments, no alpha: php.net/manual/en/function.imagecolorallocate.php The result is stored in tint_img, however, not sure it's expected, the coloring is applied to the transparent part, not the content.Mho

© 2022 - 2024 — McMap. All rights reserved.