Current Location: Home> Latest Articles> How to Use PHP and Exif Extension to Automatically Extract and Fix Photo Rotation Angle

How to Use PHP and Exif Extension to Automatically Extract and Fix Photo Rotation Angle

gitbox 2025-07-14

Extract and Fix Photo Rotation Angle Using PHP and Exif Extension

When working with photos taken from mobile phones or digital cameras, we often encounter incorrect rotation issues. To ensure photos display correctly during uploads or other operations, we can use PHP and the Exif extension to extract and fix the photo's rotation angle.

Install PHP Exif Extension

Before getting started, make sure the PHP Exif extension is installed on your server. If it is not installed, use the following command to install it:

<span class="fun">sudo apt-get install php-exif</span>

Once installed, remember to enable the Exif extension in your php.ini file by uncommenting extension=exif.

Read Photo Rotation Angle

After enabling the Exif extension, we can use PHP code to read the Exif metadata of a photo, including its rotation angle.

First, use the exif_read_data() function to read the Exif data of the photo:

<span class="fun">$exif = exif_read_data('path/to/photo.jpg');</span>

Extract Photo Rotation Angle

Once the Exif data is read, we can extract the rotation information by accessing $exif['Orientation']. The rotation angle in Exif is typically represented by an integer, which corresponds to the following:

  • 1: No rotation
  • 3: Rotate 180 degrees clockwise
  • 6: Rotate 90 degrees clockwise
  • 8: Rotate 90 degrees counterclockwise

We can calculate the correct rotation angle based on these values:

function getPhotoRotation($exifOrientation) {
    switch ($exifOrientation) {
        case 3: $rotation = 180; break;
        case 6: $rotation = 90; break;
        case 8: $rotation = -90; break;
        default: $rotation = 0;
    }
    return $rotation;
}

Rotate Photo

After extracting the rotation angle, we can use PHP's GD library to perform the actual image rotation.

First, use the imagecreatefromjpeg() function to load the image:

<span class="fun">$image = imagecreatefromjpeg('path/to/photo.jpg');</span>

Next, use the imagerotate() function to rotate the image:

<span class="fun">$rotatedImage = imagerotate($image, $rotation, 0);</span>

Finally, use imagejpeg() to save the rotated image:

<span class="fun">imagejpeg($rotatedImage, 'path/to/rotated-photo.jpg');</span>

Conclusion

By using PHP and the Exif extension, we can easily extract a photo's rotation angle and use the GD library to perform the image rotation. This method not only ensures that the photo is rotated correctly but also helps avoid display errors when uploading photos.