Convert a set of colors of an image to transparent

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
pepe_yola
Forum Newbie
Posts: 3
Joined: Mon May 17, 2010 10:19 am

Convert a set of colors of an image to transparent

Post by pepe_yola »

Hi:

I have developed a simple PHP code to convert some defined colors of an image to transparent, while keep the other colors (including transparent areas) as in the original image. The code is as follow:

Code: Select all

<?php
function Verify($Red,$Green,$Blue) {
        //Here I define the colors to convert to transparent
        
        if ($Red==245 and $Green==0 and $Blue==0) return false;
        if ($Red==196 and $Green==227 and $Blue==0 return false;
        return true;
}

$image_source = imagecreatefrompng('test.png'); 
$new_image = imagecreatetruecolor(256, 256); 
imagealphablending($new_image, false);
imagesavealpha($new_image, true);
$Fill = imagecolorallocatealpha($new_image,0,0,0,127); 
imagefill($new_image, 0, 0, $Fill);

for ($y=0;$y<256;$y++) {
        for ($x=0;$x<256;$x++) {
                $rgb = imagecolorat($image_source,$x,$y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >>8) & 0xFF;
                $b = $rgb & 0xFF;               
                if (Verify($r,$g,$b)) {imagesetpixel($new_image,$x,$y,$rgb);}           
        }
}       

header("Content-Type: image/png"); 
imagepng($new_image); 
imagedestroy($image_source);
imagedestroy($new_image);
?>
The script works very well but, as you can image, the performance is not very good. I would like to ask in this forum how to improve the performance of the code.

Thanks in advance.
Last edited by pepe_yola on Mon May 24, 2010 1:35 am, edited 2 times in total.
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Convert a set of colors of an image to transparent

Post by Christopher »

Moved to Code Critique.
(#10850)
Post Reply