Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a new image from a JPEG file using the imagecreatefromjpeg() function in PHP?
The imagecreatefromjpeg() function is an inbuilt PHP function that creates a new image resource from a JPEG file. It returns an image identifier representing the image obtained from the given filename.
Syntax
resource imagecreatefromjpeg(string $filename)
Parameters
$filename − The name or path to the JPEG image file to be loaded.
Return Value
Returns an image resource identifier on success, or false on failure.
Note: This function requires the GD extension to be enabled in PHP.
Example 1 − Basic Image Loading and Display
The following example shows how to load a JPEG image and display it in the browser ?
<?php
// Load an image from file
$img = imagecreatefromjpeg('/path/to/image.jpg');
// Set the content type header for JPEG
header('Content-type: image/jpeg');
// Output the image to browser
imagejpeg($img);
// Free up memory
imagedestroy($img);
?>
Example 2 − Image Processing with Flip
This example demonstrates loading a JPEG image, applying a flip transformation, and saving the result ?
<?php
// Load a JPEG image from file
$img = imagecreatefromjpeg('/path/to/input.jpg');
// Flip the image horizontally
imageflip($img, IMG_FLIP_HORIZONTAL);
// Save the modified image
imagejpeg($img, '/path/to/output.jpg');
// Clean up memory
imagedestroy($img);
?>
Example 3 − Error Handling
This example shows how to handle errors when loading JPEG files ?
<?php
function LoadJpeg($imgname) {
// Attempt to open the image
$im = @imagecreatefromjpeg($imgname);
// Check if loading failed
if(!$im) {
// Create a fallback image
$im = imagecreatetruecolor(700, 300);
$bgc = imagecolorallocate($im, 0, 0, 255);
$tc = imagecolorallocate($im, 255, 255, 255);
imagefilledrectangle($im, 0, 0, 700, 300, $bgc);
// Display error message on image
imagestring($im, 5, 80, 140, 'Error loading ' . $imgname, $tc);
}
return $im;
}
// Set content type
header('Content-Type: image/jpeg');
// Load image with error handling
$img = LoadJpeg('nonexistent.jpg');
imagejpeg($img);
imagedestroy($img);
?>
Key Points
| Aspect | Details |
|---|---|
| Supported Format | JPEG files only |
| Memory Usage | Always call imagedestroy() to free memory |
| Error Handling | Returns false on failure |
| Requirements | GD extension must be enabled |
Conclusion
The imagecreatefromjpeg() function is essential for loading JPEG images in PHP for further processing. Always implement proper error handling and remember to free memory with imagedestroy().
