简体   繁体   中英

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 ? Eg : In this image

在此输入图像描述

can I get the starting point,ie the x,y positions of the colour RED.

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.

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:

$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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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