使用PHP GD为PNG图像着色 [英] Colorize a PNG image using PHP GD

查看:120
本文介绍了使用PHP GD为PNG图像着色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个透明背景和白色圆圈的PNG图片.我正在尝试将白色圆圈着色为特定的颜色,但是我在使用此代码时遇到困难:

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.

推荐答案

您认为您的PNG图像具有Alpha透明度,这使得 imagecolorset() 没用,因为您将删除透明度(或最终出现锯齿状边缘).

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

如果只有一个圆,最好使用GD创建一个新图像,然后使用 imagefilledellipse() .

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

但是,如果圆"比一个圆稍微复杂一点,那么会使您的代码变得非常复杂.但是,您可以使用GD抽象库,例如 WideImage 来显着简化该任务.因此,要为透明的蒙版"着色,只需对WideImage进行以下操作:

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

除了第2步和第6步外,上述9个步骤中的大多数都可以通过GD轻松完成...仍然可以通过循环,一些数学运算以及对 imagecolorset() .

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

这篇关于使用PHP GD为PNG图像着色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆