Colorize a PNG image using PHP GD

房东的猫 提交于 2019-12-31 05:09:42

问题


I've got a PNG image with a transparent background and a white circle. I'm trying to colorize the white circle into a specific color, but I'm having difficulty using this code:

$src = imagecreatefrompng('circle.png');

$handle = imagecolorclosest($src, 255,255,255);
imagecolorset($src,$handle,100,100,100);

$new_image_name = "new_image.png";
imagepng($src,$new_image_name);
imagedestroy($src)

Any suggestions would be really helpful. Thank you in advance.


回答1:


Your PNG image I assume has alpha transparency, which makes imagecolorset() useless as you'll just remove the transparency (or end up with jagged edges).

If you have just a circle, you are better off creating a new image with GD and drawing your circle with imagefilledellipse().

However, if the "circle" is a little more complex than just a circle, that complicates your code greatly. However, you could use a GD abstraction library such as WideImage to simplify significantly that task. So, to colorize a transparent "mask", you can simply do the following with WideImage:

// 1. Load Image
$original = WideImage::load('circle.png');

// 2. Get Transparency Mask
$mask = $original->getMask();

// 3. Dispose Original
$original->destroy();

// 4. Create New Image
$colorized = WideImage::createTrueColorImage($mask->getWidth(), $mask->getHeight());

// 5. Colorize Image
$bg = $colorized ->allocateColor(255, 0, 0);
$colorized->fill(0, 0, $bg);

// 6. Apply Transparency Mask
$colorized->applyMask($mask);

// 7. Dispose mask
$mask->dispose();

// 8. Save colorized
$colorized->save($new_image_name);

// 9. Dispose colorized
$colorized->dispose();

Most of the 9 steps above can be done easily with GD except for step 2 and 6... It still can be done with a loop, some maths, and lots of calls to imagecolorat() and imagecolorset().



来源:https://stackoverflow.com/questions/5279255/colorize-a-png-image-using-php-gd

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