How to create a new image from a PNG file or URL using the imagecreatefrompng() function in PHP?

PHPServer Side ProgrammingProgramming

In PHP, imagecreatefrompng() is an inbuilt function that is used to create a new image from a PNG file or URL. imagecreatefrompng() returns an image identifier representing the image obtained from the given filename.

Syntax

resource imagecreatefrompng(string $filename)

Parameters

imagecreatefrompng() takes only one parameter, $filename. This parameter holds the name of the image or path to the PNG image.

Return Values

imagecreatefrompng() returns an image resource identifier on success, and it gives an error on false.

Example 1 − Showing the loaded PNG image in the browser

<?php
   // Load an image from local drive/file
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img29.png');
   // It will show the loaded PNG image in the browser
   header('Content-type: image/png');
   imagejpeg($img);
   imagedestroy($img);
?>

Output

Example 2 − Loaded and saving PNG image in the local drive path

<?php
   // Load an image from local drive/file
   $img = imagecreatefrompng('C:\xampp\htdocs\Images\img29.png');

   // Flip the image
   // imageflip($img,1);

   // Save the GIF image into the given local drive folder path.
   imagejpeg($img,'C:\xampp\htdocs\pic.gif');
   imagedestroy($img);
?>

Output

Explanation − In Example 2, a png image is loaded from the local path using the imagecreatefrompng() function. Then, we converted the png image to the gif image and saved it in the local drive by giving the path to save the gif image.

We can also see the image in the browser (see Example1).

raja
Updated on 09-Aug-2021 09:54:10

Advertisements