Search code examples
phpphp-gd

PHP GD: Crop polygon: Works with some images, with some not


I want to crop out a polygon (that I have there a transparent area) of an image I saved from Google Maps Static API. Then I created a second image, saved it and tried also the same script on it but with the difference that the was no effect/change on the second tried image but it's the same image. Maybe a PHP bug? I'm using PHP 5.3.3.

<?php
$image = imagecreatefrompng('map.png');
$image2 = imagecreatefrompng('map2.png');


$black = imagecolorallocatealpha($image, 0, 0, 0, 127);
$black2 = imagecolorallocatealpha($image2, 0, 0, 0, 127);


imagefilledpolygon($image, array(0,0, 20,20, 0,20), 3, $black);
imagefilledpolygon($image2, array(0,0, 20,20, 0,20), 3, $black2);

header('Content-Type: image/png');
imagepng($image);
#imagepng($image2);
?>

Image 1: 1

Image 2: 2


Solution

  • I found the solution: You have to set imagealphablending and imagesavealpha settings for the images to get this transparency working. The problem also that these images have different bits. The working images had 8bit while the not working had 24bit.

    imagealphablending($image2, false);
    imagesavealpha($image2, true);
    

    This comment helped me much: http://www.php.net/manual/en/function.imagecreatefrompng.php#47083