Home > Article > Backend Development > How to Correctly Rotate Uploaded Images Based on EXIF Orientation using PHP?
When using exif_read_data to rotate uploaded jpeg images based on their orientation, it's important to interpret the data correctly. In the provided code, the orientation is being read but not applied accurately.
The EXIF data is extracted using exif_read_data($upload_path . $newfilename), which returns an array with various metadata. The "Orientation" key holds the value indicating the image's orientation.
To fix the rotation, use the following switch statement according to the "Orientation" value:
<code class="php">switch($ort) { case 3: // Rotate 180 degrees left $image->imagerotate($upload_path . $newfilename, 180, -1); break; case 6: // Rotate 90 degrees right $image->imagerotate($upload_path . $newfilename, -90, -1); break; case 8: // Rotate 90 degrees left $image->imagerotate($upload_path . $newfilename, 90, -1); break; }</code>
Alternatively, consider these optimized functions for orientation adjustment:
This function rotates the image without resampling:
<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>
<code class="php">function image_fix_orientation(&$image, $filename) { $image = imagerotate($image, array_values([0, 0, 0, 180, 0, 0, -90, 0, 90])[@exif_read_data($filename)['Orientation'] ?: 0], 0); }</code>
This function handles image orientation within ImageMagick:
<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>
The above is the detailed content of How to Correctly Rotate Uploaded Images Based on EXIF Orientation using PHP?. For more information, please follow other related articles on the PHP Chinese website!