2010-08-06 92 views
4

我正在寻找一种转换图像的方式,以便所有非透明像素(具有alpha!= 1的像素)都变为黑白透明像素(或转换为白色)。我得到的最接近是与下面的ImageMagick命令:将不透明像素转换为黑色

convert <img> -colorspace Gray <out> 

然而,这仍然给了我一些灰色的,而不是一个完整的黑色。我尝试了所有的色彩空间选项,但没有任何工作。

任何想法,我能如何与ImageMagick的或类似的工具实现这一目标(或者如果存在一个PHP库)

回答

17

我知道这个问题已经老了,但现在我已经偶然发现了它,我不妨回答它。

你想ImageMagick的命令是:

convert <img> -alpha extract -threshold 0 -negate -transparent white <out> 

我会击穿它在做什么为好。

  1. -alpha extract - 采取阿尔法掩蔽图像的。完全透明的像素是黑色的,完全不透明的像素是白色的。
  2. -threshold 0 - 如果所有通道大于零,则将所有通道增加到最大值。在这种情况下,它将使使每个像素变成白色,除了那些完全是黑色的
  3. -negate - 倒立图像。现在我们的黑人是白人,我们的白人是黑人。
  4. -transparent white - 设置白色像素为透明。如果您希望原本透明的像素为白色,则可以排除这一点。

之前

PNG image with alpha channel

Previous image after running the convert command

1

嗯,你可以用GD和一对循环做到这一点:

$img = imagecreatefromstring(file_get_contents($imgFile)); 
$width = imagesx($img); 
$hieght = imagesy($img); 

$black = imagecolorallocate($img, 0, 0, 0); 
$white = imagecolorallocate($img, 255, 255, 255); 

for ($x = 0; $x < $width; $x++) { 
    for ($y = 0; $y < $width; $y++) { 
     $color = imagecolorat($img, $x, $y); 
     $color = imagecolorforindex($color); 
     if ($color['alpha'] == 1) { 
      imagesetpixel($img, $x, $y, $black); 
     } else { 
      imagesetpixel($img, $x, $y, $white); 
     } 
    } 
} 

或者,你可以更换颜色(这可能会或可能无法正常工作):

$img = imagecreatefromstring(file_get_contents($imgFile)); 
$maxcolors = imagecolorstotal($img); 
for ($i = 1; $i <= $maxcolors; $i++) { 
    $color = imagecolorforindex($i); 
    if ($color['alpha'] == 1) { 
     imagecolorset($img, $i, 0, 0, 0); 
    } else { 
     imagecolorset($img, $i, 255, 255, 255); 
    } 
}