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

PHPServer Side ProgrammingProgramming

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.


resource imagecreatefromjpeg(string $filename)


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

   // 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');


Example 2

   // 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.

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

   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');


Updated on 09-Aug-2021 09:48:33