2010-08-06 58 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); 
    } 
} 
相關問題