PHP/GD - transparent background

Spinal picture Spinal · Mar 6, 2013 · Viewed 19.2k times · Source

I want to do the following in PHP in combination with GD. ImageMagick is not an option, unfortunately, but this seems like such a common problem that there has to be a solution, I just can't seem to find it.

I want to create a PNG with a transparent background. Then I want to draw a rectangle on it, copy an image on it, and add some text. One way of doing this is as follows:

$image = ImageCreateTrueColor (800, 600);
imagecolortransparent ($image, 0); //0 is pure black, the default fill color
imagerectangle (...);
//code to copy an image
imagettftext ($image, ...);
imagepng ($image);

This works fine, except that part of the copied image might be black, and/or the text might be black. This then also becomes transparent, which is something I don't want.

imagefill ($image, 0,0, 0x7FFF0000);
imagetransparent ($image, 0x7FFF0000);

The above code is something I found online, which fills it with red, then makes red transparent. Again, this causes all red in the image to become transparent. I could choose a color that is unlikely to occur, but I can't guarantee this.

Is there something I'm missing? Can this be fixed? Thanks for your replies!

Answer

Rudi Visser picture Rudi Visser · Mar 6, 2013

imagecolortransparent is probably not what you want here if you're merging images, as single-colour transparency is nasty.

Instead, try it with a transparent fill mask like so:

<?php
$image = imagecreatetruecolor(100, 100);

// Transparent Background
imagealphablending($image, false);
$transparency = imagecolorallocatealpha($image, 0, 0, 0, 127);
imagefill($image, 0, 0, $transparency);
imagesavealpha($image, true);

// Drawing over
$black = imagecolorallocate($image, 0, 0, 0);
imagefilledrectangle($image, 25, 25, 75, 75, $black);

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