PHP Replacing white color in a transparent image

Viewed 194

I am working on a php script that replaces the white color with a given one. This is the source image I'm working with:

This is what I'm trying to accomplish:

The first script I tried:

    $im = imagecreatefrompng("taxi.png");

    imagefilter($im, IMG_FILTER_NEGATE); 
    imagefilter($im, IMG_FILTER_COLORIZE, 0, 255, 255); 
    imagefilter($im, IMG_FILTER_NEGATE); 

    imagealphablending( $im, false );
    imagesavealpha( $im, true );
    imagepng($im);
    imagedestroy($im);

This looked like this:

The second time I tried replacing the each pixel which resulted in having no tolerance, if a pixel was just 1 unit off it wouldn't get replaced.

function ReplaceColour($img, $r1, $g1, $b1, $r2, $g2, $b2)
{
    if(!imageistruecolor($img))
        imagepalettetotruecolor($img);
    $col1 = (($r1 & 0xFF) << 16) + (($g1 & 0xFF) << 8) + ($b1 & 0xFF);
    $col2 = (($r2 & 0xFF) << 16) + (($g2 & 0xFF) << 8) + ($b2 & 0xFF);

    $width = imagesx($img); 
    $height = imagesy($img);
    for($x=0; $x < $width; $x++)
        for($y=0; $y < $height; $y++)
        {
            $colrgb = imagecolorat($img, $x, $y);
            if($col1 !== $colrgb)
                continue; 
            imagesetpixel ($img, $x , $y , $col2);
        }   
}

header('Content-Type: image/png');
$im = imagecreatefrompng("taxi.png");

ReplaceColour($im,245,245,245,255,0,0);

imagealphablending( $im, false );
imagesavealpha( $im, true );
imagepng($im);
imagedestroy($im);

At the moment I'm thinking about making a mask for the image and changing the mask's color on the fly, but the problem is that I would have to create it for every image I'm adding.

0 Answers
Related