Search code examples
phpimagepngimagecreatefrompng

Create a transparent png file using PHP


Currently I would like to create a transparent png with the lowest quality .

The code:

<?php
function createImg ($src, $dst, $width, $height, $quality) {
    $newImage = imagecreatetruecolor($width,$height);
    $source = imagecreatefrompng($src); //imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.
    imagecopyresampled($newImage,$source,0,0,0,0,$width,$height,$width,$height);
    imagepng($newImage,$dst,$quality);      //imagepng() creates a PNG file from the given image. 
    return $dst;
}

createImg ('test.png','test.png','1920','1080','1');
?>

However, there are some problems:

  1. Do I need to specific a png file before creating any new file? Or can I create without any existing png file?

    Warning: imagecreatefrompng(test.png): failed to open stream: No such file or directory in

    C:\DSPadmin\DEV\ajax_optipng1.5\create.php on line 4

  2. Although there are error message , it still generate a png file , however, what I found that is the file is a black color image , do I need to specific any parameter to make it transparent?

Thanks.


Solution

  • To 1) imagecreatefrompng('test.png') tries to open the file test.png which then can be edited with GD functions.

    To 2) To enable saving of the alpha channel imagesavealpha($img, true); is used. The following code creates a 200x200px sized transparent image by enabling alpha saving and filling it with transparency.

    <?php
    $img = imagecreatetruecolor(200, 200);
    imagesavealpha($img, true);
    $color = imagecolorallocatealpha($img, 0, 0, 0, 127);
    imagefill($img, 0, 0, $color);
    imagepng($img, 'test.png');