且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用PHP在图像中用另一种颜色替换

更新时间:2022-12-17 12:16:00

如果您打算在PHP中使用GD库,则应检查

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.