2011-05-09 29 views
1

我想遍歷圖像中的每一行和每列,並用不同顏色替換某些像素。我接受使用GD或ImageMagick的解決方案。任何人都可以給我一個如何做到這一點的例子嗎?我搜索了幾種不同的方法,但沒有找到一個可靠的例子。如何在PHP中替換圖像中的像素?

回答

7

您可以像使用GD實現這一目標:

你將處理顏色的十六進制值

function replaceColor($img, $from, $to) { 
    $r = hexdec(substr($to, 0, 2)); 
    $g = hexdec(substr($to, 2, 2)); 
    $b = hexdec(substr($to, 4, 2)); 

    // allocate $to color. 
    $to = imagecolorallocate($img, $r, $g, $b); 

    // pixel by pixel grid. 
    for ($y = 0; $y < imagesy($img); $y++) { 
     for ($x = 0; $x < imagesx($img); $x++) { 

      // find hex at x,y 
      $at = imagecolorat($img, $x, $y); 
      $r = 0xFF & ($at >> 0x10); 
      $g = 0xFF & ($at >> 0x8); 
      $b = 0xFF & ($at); 
      $hex = dechex($r).dechex($g).dechex($b); 

      // set $from to $to if hex matches. 
      if ($hex == $from) { 
       imagesetpixel($img, $x, $y, $to); 
      } 
     } 
    } 
} 
+1

也許應該指定在$從/ $以顏色作爲字符串提供格式'RRGGBB'十六進制值。 – mpen 2011-05-09 03:42:53

+0

^^這。我希望OP會意識到:P +1謝謝 – Atticus 2011-05-09 03:44:26

+0

只是好奇,但是當X和Y之間的某個位置有顏色時,是否會改變顏色?我不知道這是可能的顏色.. – 2011-05-09 04:45:01