PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 10, 2022

[FIXED] How can I replace one color with another in a png 24 alpha transparent image with GD

 October 10, 2022     gd, image-processing, php     No comments   

Issue

I have tried:

$index = imagecolorresolve ( $im,  0,0,0 ); // get black
imagecolorset($im, $index, 255, 0, 255); // SET NEW COLOR

This seems to work with png 8 but not 24, and if I do it with 8 it turns out all weird because of the anti-aliasing.

Here is the full test code I'm using. (this is just test code, so be gentle).

function LoadPNG($imgname, $color = false)
{        
    $im = @imagecreatefrompng($imgname);
    imagealphablending($im, false); 

    if($color) {
      $index = imagecolorresolve ( $im,  0,0,0 ); // get black
      imagecolorset($im, $index, 255, 0, 255); // SET NEW COLOR
    }

    imageAlphaBlending($im, true);
    imageSaveAlpha($im, true);

    return $im;
}

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

$img = LoadPNG("head.png", "red");

imagepng($img);
imagedestroy($img);

Solution

You can try the following:

  • cycle all points
  • get the color of that point
  • if it matches your colorA, set that pixel to the desired colorB

Code:

for ($x=imagesx($im); $x--; ) {
    for ($y=imagesy($im); $y--; ) {
        $c = imagecolorat($im, $x, $y);
        if ($c[0] == 0 && $c[1] == 0 && $c[2] == 0) {
            // here we use the new color, but the original alpha channel
            $colorB = imagecolorallocatealpha($im, 255, 0, 255, $c[3]);
            imagesetpixel($im, $x, $y, $colorB);
        }
    }
}

Hope this helps!



Answered By - aorcsik
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing