Open In App

PHP | imagepng() Function

Improve
Improve
Like Article
Like
Save
Share
Report

The imagepng() function is an inbuilt function in PHP which is used to display image to browser or file. The main use of this function is to view an image in the browser, convert any other image type to PNG and applying filters to the image.

Syntax:

bool imagepng( resource $image, int $to, int $quality, int $filters)

Parameters: This function accepts three parameters as mentioned above and described below:

  • $image: It specifies the image resource to work on.
  • $to (Optional): It specifies the path to save the file to.
  • $quality (Optional): It specifies the quality of the image.
  • $filters (Optional): It specifies the filters to apply to the image which help in reducing the image size.

Return Value: This function returns TRUE on success or FALSE on error.

Below examples illustrate the imagepng() function in PHP:

Example 1: In this example we will be viewing an image in browser.

php




<?php
  
// Load an image from PNG URL
$im = imagecreatefrompng(
  
// View the loaded image in browser using imagepng() function
header('Content-type: image/png');  
imagepng($im);
imagedestroy($im);
?>


Output:

Example 2: IN this example we will convert JPEG into PNG.

php




<?php
  
// Load an image from JPEG URL
$im = imagecreatefromjpeg(
  
// Convert the image into PNG using imagepng() function
imagepng($im, 'converted.png');
imagedestroy($im);
?>


Output:

This will save the PNG version of image in the same folder where your PHP script is.

Program 3: In this example we will use filters.

php




<?php
  
// Create an image instance
$im = imagecreatefrompng(
  
// Save the image as image1.png
imagepng($im, 'image1.png');
  
// Save the image as image2.png with all filters to disable size compression
imagepng($im, 'image2.png', null, PNG_ALL_FILTERS);
  
imagedestroy($im);
?>


Output:

This will save the image1.png as compressed and image2.png as uncompressed image

Reference: https://www.php.net/manual/en/function.imagepng.php



Last Updated : 29 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads