PHP: transparent area in PNG

I want to create a transparent area in a png image, something like a โ€œholeโ€. Therefore, I could place this image on top of some background image and see a fragment of the background through this โ€œholeโ€. I found this code on some forum:

$imgPath = 'before.png'; $img = imagecreatefrompng($imgPath); // load the image list($width,$height) = getimagesize($imgPath); // get its size $c = imagecolortransparent($img,imagecolorallocate($img,255,1,254)); // create transparent color, (255,1,254) is a color that won't likely occur in your image $border = 10; imagefilledrectangle($img, $border, $border, $width-$border, $height-$border, $c); // draw transparent box imagepng($img,'after.png'); // save 

It works to create a transparent area (rectangular in this case) in the png image. But when I put this png image on top of another image, the area loses its transparency, so I end up with a colored rectangle in the middle of the resulting image. Can someone please help me?

+4
source share
2 answers

An alternative would be to use the PHP ImageMagick extension, Imagick .

You can create a rectangle by setting the background parameter Imagick :: newImage , cicle using ImagickDraw :: circle , and the key is to apply the circle using Imagick :: compositeImage and only copy transparency . This will not allow you to have a solid image with a transparent circle on top; everything that is transparent in the mask will be transparent in the original image.

The code below should do the trick (although I'm sure it will need a few tweaks to meet your needs: P):

 <?php $base = new Imagick("before.png"); $base->cropImage(512, 512, 0, 0); $base->setImageMatte(true); $mask = new Imagick(); $mask->newImage(512, 512, new ImagickPixel("transparent")); $circle = new ImagickDraw(); $circle->setFillColor("black"); $circle->circle(150, 150, 100, 100); $mask->drawImage($circle); $base->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0); $base->writeImage('after.png'); header("Content-Type: image/png"); echo $base; ?> 
+1
source

Try this for a transparent color:

 $c = imagecolorallocatealpha($img,0,0,0,127); 
0
source

All Articles