PHP Read EXIF Data and Adjust Image Orientation
When uploading images, especially from mobile devices, it's crucial to ensure their orientation is corrected. This is achieved by reading the EXIF data and manipulating the image accordingly.
EXIF Data Reading
The exif_read_data() function is used to read the EXIF information from the uploaded JPEG image. For instance:
<code class="php">$exif = exif_read_data($upload_path . $newfilename);</code>
The result, stored in $exif, contains various information, including orientation data.
Orientation Adjustment
To correct the orientation, inspect the EXIF data's Orientation field. Common values include:
Based on the orientation value, apply the appropriate transformation using image manipulation functions like imagerotate() or rotateImage().
Addressing Common Issues with iPhone and Android Images
Your code may encounter issues with images from iPhones and Android devices because they often embed EXIF data in a non-standard way. To address this, consider using GD or ImageMagick functions for orientation correction.
GD Function
<code class="php">function image_fix_orientation(&$image, $filename) { $exif = exif_read_data($filename); if (!empty($exif['Orientation'])) { switch ($exif['Orientation']) { case 3: $image = imagerotate($image, 180, 0); break; case 6: $image = imagerotate($image, 90, 0); break; case 8: $image = imagerotate($image, -90, 0); break; } } }</code>
ImageMagick Function
<code class="php">function image_fix_orientation($image) { if (method_exists($image, 'getImageProperty')) { $orientation = $image->getImageProperty('exif:Orientation'); } else { $filename = $image->getImageFilename(); if (empty($filename)) { $filename = 'data://image/jpeg;base64,' . base64_encode($image->getImageBlob()); } $exif = exif_read_data($filename); $orientation = isset($exif['Orientation']) ? $exif['Orientation'] : null; } if (!empty($orientation)) { switch ($orientation) { case 3: $image->rotateImage('#000000', 180); break; case 6: $image->rotateImage('#000000', 90); break; case 8: $image->rotateImage('#000000', -90); break; } } }</code>
These functions adjust the image orientation without resampling, preserving the image quality.
The above is the detailed content of How to Correct Image Orientation When Uploading Images from Mobile Devices?. For more information, please follow other related articles on the PHP Chinese website!