Changing the color of opaque parts of png in PHP

I want to fill a png opaque part with any color or image using php.

Below is the basic image

transparent cat

Below is the target image

colored cat

I used the following php code to fill in the opaque portion of the png.

$im = imagecreatefrompng(dirname(__FILE__) . '/images/cat_1.png');
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im, 0, 0, $red);
header('Content-type: image/png');


But this gives me the following result.

wrong output of cat

please help me to complete my task.

Thanks in advance.


source to share

3 answers

Save this version of the base image:

Base image

This image was saved as an indexed PNG format, making it ideal for color replacement. In this case, index 0 is the color of the cat and index 1 is the background (not perfect, but the one GIMP gave me)

In this case:

$img = imagecreatefrompng("cat_1.png");
imagecolorset($img,0, 255,0,0);
imagepng($img); // output red cat


Editing images in general is much easier if you have a base image that makes editing easier this way;)



This line imagefill($im, 0, 0, $red);

fills the image with red, at the coordinate (0,0), which should be filled. So it starts filling up in the top left corner and fills in everything just like using PaintBucket in MSPaint. For example you can use imagefill($im, 150, 150, $red);

(if 150 150 is the center).



use this function, it returns base64 image <img src="output">

public static function colorImage($url, $hex = null, $r = null, $g = null, $b = null)

    if ($hex != null) {
        $hex = str_replace("#", "", $hex);
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
    $im = imagecreatefrompng($url);
    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 | $r << 16 | $g << 8 | $b;
                imagesetpixel($im, $x, $y, $newColor);

    $image_data = ob_get_contents();


    $image_data_base64 = "data:image/png;base64," . base64_encode($image_data);

    return $image_data_base64;




All Articles