[英]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.