Page 1 of 1

[solved] Problem on overlaying translucent images (GD)

Posted: Mon Mar 31, 2008 4:50 am
by davidpage
Hi all,

In php if I draw two translucent shapes with some parts of the one overlaying on the other, the overlaid parts will have a darker colour:

i.e. the following code...

Code: Select all

<?php
 $im = ImageCreateTrueColor(150,150);
 $blue = ImageColorAllocate($im,150,150,255);
 ImageFilledRectangle($im,0,0,150,150,$blue);
 $gray = ImageColorResolveAlpha($im,70,70,70,63);
 ImageFilledRectangle($im,10,10,80,80,$gray);
 ImageFilledRectangle($im,60,60,120,120,$gray);
 header('Content-Type: image/png');
 ImagePNG($im);
?>
... will give an image as follows:
Image

However, what should I do in order to eliminate the discrepancy in the colour of the two areas (the overlaid parts have the same colour as the non-overlaid parts)? i.e. I'm planning to create a image like the following (I've added a red circle to show that the gray area is really translucent)...

Image

...which I made using the following code:

Code: Select all

<?php
 $im = ImageCreateTrueColor(150,150);
 $blue = ImageColorAllocate($im,150,150,255);
 $red = ImageColorAllocate($im,255,0,0);
 ImageFilledRectangle($im,0,0,150,150,$blue);
 $gray = ImageColorResolveAlpha($im,70,70,70,63);
 ImageFilledEllipse($im,50,90,40,40,$red);
 ImageFilledPolygon($im,array(10,10,10,80,60,80,60,120,120,120,120,60,80,60,80,10),8,$gray);
 header('Content-Type: image/png');
 ImagePNG($im);
?>

In my actual project, the areas are of course more complex than this simple rectangle problem, and so I need an easier way to achieve this, e.g. by adding a suitable command while I draw the rectangles (or ellipses or polygons).

Thanks!

Re: Problem on overlaying translucent images (GD)

Posted: Mon Mar 31, 2008 5:48 am
by onion2k
I think your best option will be to abandon the translucent colours completely. Instead, create a new transparent image*, draw your rectangle shapes on it as solid blocks, then use imagecopymerge() with the percentage parameter set to whatever the translucency should be to copy it to your destination image.

* http://www.phpgd.com/scripts.php?script=27

Re: Problem on overlaying translucent images (GD)

Posted: Tue Apr 01, 2008 4:25 am
by davidpage
Thanks onion2k! I've used your suggested method and it worked perfectly fine.