In web development, it's common to save user-uploaded or remote images to the server. However, images taken with mobile phones or cameras often come with orientation issues because of how devices store rotation data in the image's metadata. To ensure images display correctly, we need to handle this rotation information when saving the image.
First, we need to download the image using its remote URL and save it locally. PHP's file_get_contents() and file_put_contents() functions can be used for this purpose:
$url = 'URL of the remote image';
$image = file_get_contents($url);
// Filename and save path
$filename = 'saved-image.jpg';
$save_path = 'path/to/save/';
file_put_contents($save_path . $filename, $image);
JPEG images usually contain orientation data in their Exif metadata. We can extract this using PHP's exif_read_data() function:
// Get orientation using Exif extension
$exif = exif_read_data($save_path . $filename);
if (!empty($exif['Orientation'])) {
// Adjust image based on orientation
switch ($exif['Orientation']) {
case 3:
// Rotate 180 degrees
$image = imagerotate($image, 180, 0);
break;
case 6:
// Rotate 90 degrees clockwise
$image = imagerotate($image, -90, 0);
break;
case 8:
// Rotate 90 degrees counter-clockwise
$image = imagerotate($image, 90, 0);
break;
}
}
// Save the rotated image
file_put_contents($save_path . $filename, $image);
The code above checks the image's Exif metadata for the Orientation field and uses imagerotate() to fix it if needed. Here are a few things to keep in mind:
By using the above approach, developers can automatically correct the orientation of remote images when saving them with PHP. This improves the accuracy of image display and enhances the user experience, particularly in image upload systems and mobile applications.