問題描述
如何在 PHP 中為透明的 PNG 文件著色? (How can I tint transparent PNG files in PHP?)
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
‑‑‑‑‑
參考解法
方法 1:
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.
方法 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");
?>
(by James Hall、nunespascal、pix0r)