简体   繁体   English

在图像中找到指定颜色的x,y位置?

[英]Find x,y position of a specified colour in an image?

Is there any way to get the x,y position of a colour in an image in PHP ? 有没有办法在PHP中获取图像中颜色的x,y位置? Eg : In this image 例如:在这张图片中

在此输入图像描述

can I get the starting point,ie the x,y positions of the colour RED. 我可以得到起点,即颜色RED的x,y位置。

I need to create an option for the user to change the colour of a particular portion in an image.So if the user wants to change the red colour to blue in this image.I use imagefill() function to change the colour,but it need the x,y coordinates to work.Hope this make sense. 我需要为用户创建一个选项来更改图像中特定部分的颜色。如果用户想要在此图像中将红色更改为蓝色。我使用imagefill()函数来更改颜色,但它需要x,y坐标才能工作。希望这是有道理的。

Try something like this: 尝试这样的事情:

// 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);
}

We are expecting here that $findColor and $replaceColor are arrays with this structure: 我们在这里期望$findColor$replaceColor是具有这种结构的数组:

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

Didn't try the code but it at least should point You the right way. 没试过代码,但它至少应该指出你正确的方式。 It loops through every pixel, check the color at that pixel and if it is the one we are looking for, replaces it with the $replaceColor . 它循环遍历每个像素,检查该像素的颜色,如果它是我们正在寻找的那个,则用$replaceColor替换它。 If not, the very same color is then placed into the new image at the very same position. 如果没有,则将相同的颜色放置在同一位置的新图像中。

As it uses two for loops it may be very time and memory consumpting on large images. 因为它使用两个for循环,它可能是非常时间和内存消耗在大图像上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM