Current Location: Home> Latest Articles> How to Correct Image Orientation When Saving Remote Images with PHP

How to Correct Image Orientation When Saving Remote Images with PHP

M66 2025-07-01

How to Properly Save and Handle Image Orientation in PHP

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.

Downloading a Remote Image to Local Storage

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

Reading Exif Metadata to Get Image Orientation

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

Important Notes When Rotating Images

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:

  • Make sure the GD extension is enabled, as imagerotate() is a GD library function.
  • Only JPEG images typically contain full Exif data—PNG and other formats usually do not.
  • Some platforms may already auto-correct image orientation upon upload, so verify the orientation data first.

Conclusion

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.