用PHP在图像中用另一种颜色替换 [英] Replace a color with another in an image with PHP
问题描述
有人可以用一个简单的脚本帮助我,用PHP将图像中的特定颜色替换为另一种颜色吗? 这是一个示例(颜色从绿色变为黄色).
Can someone help me with a simple script to replace a specific color with another color in an image using PHP? Here is a example (color changed from green to yellow).
推荐答案
If you meant using GD library in PHP, you should give a check on imagefilter()
步骤是:
- 从.PNG图像开始,内部使用白色,外部使用alpha.
- 使用
imagefilter($img, IMG_FILTER_COLORIZE, 0, 255, 0))
其中0,255,0是您的RGB颜色(在此示例中为亮绿色) - 保存Alpha并打印出结果.
- Start with a .PNG image, use white for inner, alpha for outer.
- Use
imagefilter($img, IMG_FILTER_COLORIZE, 0, 255, 0))
Where 0,255,0 is your RGB color (bright green in this example) - Save the alpha and print out result.
编辑,工作代码和说明.
Edit, Working code and clarification.
我的意思是,对黑色线条的外部使用alpha,对白色线条内部使用.这是示例图片:
I meant, using alpha for OUTER of the black lines, and white INSIDE. Here's the sample image:
这是为白色零件着色的有效代码:
And here's a working code for colorizing white parts:
header('Content-Type: image/png');
/* RGB of your inside color */
$rgb = array(0,0,255);
/* Your file */
$file="../test.png";
/* Negative values, don't edit */
$rgb = array(255-$rgb[0],255-$rgb[1],255-$rgb[2]);
$im = imagecreatefrompng($file);
imagefilter($im, IMG_FILTER_NEGATE);
imagefilter($im, IMG_FILTER_COLORIZE, $rgb[0], $rgb[1], $rgb[2]);
imagefilter($im, IMG_FILTER_NEGATE);
imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng($im);
imagedestroy($im);
注意:由于colorize仅适用于非白色部分,因此我们必须取反值.我们可以通过内部带有黑色边框的白色边框图像来解决此问题.
Note: We must negate values since colorize only works for non-white parts. We could have a workaround to this by having white-bordered image with black inside.
注意:此代码仅适用于黑白和黑白图像.
Note: This code only works for black-border and white-inner images.
这篇关于用PHP在图像中用另一种颜色替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!