How to create a new image from a JPEG file using the imagecreatefromjpeg() function in PHP?


imagecreatefromjpeg() is an inbuilt function in PHP that is used to create a new image from a JPEG file. It returns an image identifier representing the image obtained from the given filename.

Syntax

resource imagecreatefromjpeg(string $filename)

Parameters

imagecreatefromjpeg() uses only one parameter, $filename, that holds the name of the image or path to the JPEG image.

Return Values

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

Example 1

<?php
   // Load an image from local drive/file
   $img = imagecreatefromjpeg('C:\xampp\htdocs\test\1.jpeg');
   
   // it will show the loaded image in the browser
   header('Content-type: image/jpg');
   
   imagejpeg($img);
   
   imagedestroy($img);
?>

Output

Example 2

<?php
   // Load a JPEG image from local drive/file
   $img = imagecreatefromjpeg('C:\xampp\htdocs\test\1(a).jpeg');
   
   // Flip the image
   imageflip($img, 1);
   
   // Save the GIF image in the given path.
   imagejpeg($img,'C:\xampp\htdocs\test\1(b).png');
   imagedestroy($img);
?>

Input Image

Output Image

Explanation − In Example 2, we loaded the jpeg image from the local path using the imagecreatefromjpeg() function. Thereafter, we used the imageflip() function to flip the image.

Example 3 − Handling errors during loading of a JPEG image

<?php
   function LoadJpeg($imgname) {
      /* Attempt to open */
      $im = @imagecreatefromjpeg($imgname);
     
      /* See if it failed */
      if(!$im) {
         /* Create a black image */
         $im = imagecreatetruecolor(700, 300);
         $bgc = imagecolorallocate($im, 0, 0, 255);
         $tc = imagecolorallocate($im, 255,255, 255);
         imagefilledrectangle($im, 0, 0, 700, 300, $bgc);
         
         /* Output an error message */
         imagestring($im, 20, 80, 80, 'Error loading ' . $imgname, $tc);
      }
      return $im;
   }
   header('Content-Type: image/jpeg');
   $img = LoadJpeg('bogus.image');
   imagejpeg($img);
   imagedestroy($img);
?>

Output

Updated on: 09-Aug-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements