开发者

Colorize a PNG image using PHP GD

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,$hand开发者_如何学运维le,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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜