[英]Find x,y position of a specified colour in an image?
有沒有辦法在PHP中獲取圖像中顏色的x,y位置? 例如:在這張圖片中
我可以得到起點,即顏色RED的x,y位置。
我需要為用戶創建一個選項來更改圖像中特定部分的顏色。如果用戶想要在此圖像中將紅色更改為藍色。我使用imagefill()函數來更改顏色,但它需要x,y坐標才能工作。希望這是有道理的。
嘗試這樣的事情:
// 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
循環,它可能是非常時間和內存消耗在大圖像上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.