Colorize a PNG image using PHP GD

微笑、不失礼 提交于 2019-12-02 09:50:58

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().

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