How can I tint transparent PNG files in PHP?

南楼画角 提交于 2019-12-22 10:32:42

问题


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");

?>


来源:https://stackoverflow.com/questions/951960/how-can-i-tint-transparent-png-files-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!