The imagejpeg() 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 JPEG and altering the quality of the image.
Syntax:
php
Output:
Example 2: In this example we will convert PNG into JPEG.
php
Output:
php
Output:
Reference: https://www.php.net/manual/en/function.imagejpeg.php
bool imagejpeg( resource $image, int $to, int $quality )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.
<?php
// Load an image from jpeg URL
$im = imagecreatefromjpeg(
'https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg');
// View the loaded image in browser using imagejpeg() function
header('Content-type: image/jpg');
imagejpeg($im);
imagedestroy($im);
?>
Example 2: In this example we will convert PNG into JPEG.
<?php
// Load an image from PNG URL
$im = imagecreatefrompng(
'https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-13.png');
// Convert the image into JPEG using imagejpeg() function
imagejpeg($im, 'converted.jpg');
imagedestroy($im);
?>
This will save the JPEG version of image in the same folder where your PHP script is.Example 3: In this example we will alter the quality of the image.
<?php
// Load an image from jpeg URL
$im = imagecreatefromjpeg(
'https://media.geeksforgeeks.org/wp-content/uploads/20200123100652/geeksforgeeks12.jpg');
// View the loaded image in browser using imagejpeg() function
header('Content-type: image/jpg');
// Decrease the quality of image to 2
imagejpeg($im, null, 2);
imagedestroy($im);
?>
Reference: https://www.php.net/manual/en/function.imagejpeg.php