Alexander
Alexander

Reputation: 61

How to replace pixels in an image in PHP?

I'd like to loop through each row and column in an image and replace certain pixels with different colors. I am open to a solution using GD or ImageMagick. Can anyone give me an example of how to do this? I've Googled several different ways and haven't found a solid example.

Upvotes: 1

Views: 1568

Answers (1)

Atticus
Atticus

Reputation: 6720

You can achieve this with GD by something like:

You will be handling colors as hex values

function replaceColor($img, $from, $to) {
    $r = hexdec(substr($to, 0, 2));
    $g = hexdec(substr($to, 2, 2));
    $b = hexdec(substr($to, 4, 2));

    // allocate $to color.
    $to = imagecolorallocate($img, $r, $g, $b);

    // pixel by pixel grid.
    for ($y = 0; $y < imagesy($img); $y++) {
        for ($x = 0; $x < imagesx($img); $x++) {

            // find hex at x,y
            $at = imagecolorat($img, $x, $y);
            $r = 0xFF & ($at >> 0x10);
            $g = 0xFF & ($at >> 0x8);
            $b = 0xFF & ($at);
            $hex = dechex($r).dechex($g).dechex($b);

            // set $from to $to if hex matches.
            if ($hex == $from) {
                imagesetpixel($img, $x, $y, $to);
            }
        }
    }
}

Upvotes: 7

Related Questions