[solved] Problem on overlaying translucent images (GD)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
davidpage
Forum Newbie
Posts: 2
Joined: Mon Mar 31, 2008 4:46 am

[solved] Problem on overlaying translucent images (GD)

Post 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!
Last edited by davidpage on Tue Apr 01, 2008 4:25 am, edited 1 time in total.
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Re: Problem on overlaying translucent images (GD)

Post 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
davidpage
Forum Newbie
Posts: 2
Joined: Mon Mar 31, 2008 4:46 am

Re: Problem on overlaying translucent images (GD)

Post by davidpage »

Thanks onion2k! I've used your suggested method and it worked perfectly fine.
Post Reply