2012-11-05 48 views
0

有什麼辦法可以在PHP中獲取圖像中顏色的x,y位置? 例如:在此圖像中查找圖像中指定顏色的x,y位置?

enter image description here

可我得到的出發點,即X,紅色的y位置。

我需要爲用戶創建一個選項來更改圖像中特定部分的顏色。因此,如果用戶想在此圖像中將紅色更改爲藍色,我使用imagefill()函數更改顏色,但它需要x,y座標來工作。希望這是有道理的。

+0

http://php.net/manual/en/function.imagecolorat.php在一個循環中,但它會很大的圖像 –

+1

你是什麼意思_red_ __開始point_ _?具有最高_x_座標的像素?或_y_?另外,什麼是_red_? _R_分量高於_B_和_G_的顏色十六進制值? – Halcyon

+0

@MarcB我認爲他/他想要反過來,所以它可能是http://www.php.net/manual/en/function.imagecolorexact.php和/或http://www.php.net/manual /en/function.imagecolorclosest.php代替 – Gordon

回答

1

嘗試這樣:

// applied only to a PNG images, You can add the other format image loading for Yourself 
function changeTheColor($image, $findColor, $replaceColor) { 
    $img = imagecreatefrompng($image); 
    $x = imagesx($img); 
    $y = imagesy($img); 
    $newImg = imagecreate($x, $y); 
    $bgColor = imagecolorallocate($newImg, 0, 0, 0); 

    for($i = 0; $i < $x; $i++) { 
     for($j = 0; $j < $y; $j++) { 
      $ima = imagecolorat($img, $i, $j); 
      $oldColor = imagecolorsforindex($img, $ima); 
      if($oldColor['red'] == $findColor['red'] && $oldColor['green'] == $findColor['green'] && $oldColor['blue'] == $findColor['blue'] && $oldColor['alpha'] == $findColor['alpha']) 
       $ima = imagecolorallocatealpha($newImage, $replaceColor['red'], $replaceColor['green'], $replaceColor['blue'], $replaceColor['alpha']); 
      } 
      imagesetpixel($newImg, $i, $j, $ima); 
     } 
    } 

    return imagepng($newImg); 
} 

在此,我們期待的是$findColor$replaceColor與此結構數組:

$color = array(
    'red' => 0, 
    'green' => 0, 
    'blue' => 0, 
    'alpha' => 0, 
); 

沒試過的代碼,但它至少應該指向你正確的方式。它遍歷每個像素,檢查該像素的顏色,如果它是我們正在尋找的像素,則用$replaceColor替換它。如果不是,則在相同的位置將相同的顏色放入新圖像中。

因爲它使用了兩個for循環,所以在大型圖像上可能會耗費大量時間和內存。

相關問題