Question

I an trying to change color of a png image so that transparent area still remain transparent and give rest of the image a color this is what i tried

<?php

$im = imagecreatefrompng('2.png');
$w = imagesx($im);
$h = imagesy($im);

$om = imagecreatetruecolor($w,$h);

for ($x = 0; $x < $w; $x++) {
    for ($y = 0; $y < $h; $y++) {
        $rgb = imagecolorat($im, $x, $y);
        $colors = imagecolorsforindex($im,  $rgb);

        $orgb = imagecolorallocate($om,$colors['alpha'],$colors['alpha'],$colors['alpha']);
        imagesetpixel($om,$x,$y,$orgb);
    }
}

header('Content-Type: image/png');
imagepng($om);

imagedestroy($om);
imagedestroy($im);

?>   

It produce image like: Before

enter image description here

After

enter image description here

i am still not getting an exact idea how can i get highlighted area of png image and give them a color such as yellow or pink without loosing transparency so that only non-transparent area will get remain transparent

Was it helpful?

Solution

You should be able to work with the palette instead of going through every pixel in that case:

<?PHP
    $myRed = 255;
    $myGreen = 0;
    $myBlue = 0;

    $im = imagecreatefrompng('http://s25.postimg.org/ll0dzblan/image.png');
    imageAlphaBlending($im, true);
    imageSaveAlpha($im, true);

    if (imageistruecolor($im))
    {
        $sx = imagesx($im);
        $sy = imagesy($im);
        for ($x = 0; $x < $sx; $x++)
        {
            for ($y = 0; $y < $sy; $y++)
            {
                $c = imagecolorat($im, $x, $y);
                $a = $c & 0xFF000000;
                $newColor = $a | $myRed << 16 | $myGreen << 8 | $myBlue;
                imagesetpixel($im, $x, $y, $newColor );
            }
        }
    } else {
        $numColors = imagecolorstotal($im);
        $transparent = imagecolortransparent($im);

        for ($i=0; $i < $numColors; $i++)
        {
            if ($i != $transparent)
                imagecolorset($im, $i, $myRed, $myGreen, $myBlue, $myAlpha);

        }
    }

    header('Content-Type: image/png');
    imagepng($im);
    imagedestroy($im);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top