Page 1 of 1

Convert a set of colors of an image to transparent

Posted: Mon May 17, 2010 10:27 am
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 code works very well but, as you can image, the performance is not very good. I would like to share this code and ask to this comunity how to improve the performance of the code.

Thanks in advance.

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

Posted: Wed May 19, 2010 5:22 am
by Benjamin
You are getting and checking 65,536 individual pixels. To speed this up you would need to find a fast way to read the RGB value of every pixel into a lookup table. You could then quickly find all matching colors and set just those pixels.

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

Posted: Thu May 20, 2010 2:55 am
by pepe_yola
Please Benjamin, could you be more specific in your sugestion?

Thank you,

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

Posted: Thu May 20, 2010 4:30 am
by Benjamin
Not really. It's something I would need to research. Some of our members have specific experience working with images. If they see this thread I'm sure they can either give you advice or tell you it's not possible and to a low level language such as C++.