19 August 2023

While iPhones and many modern cameras save images with orientation information in their EXIF data, the correct display of these images can sometimes be an issue on other devices or in browsers. Being aware of this and employing the appropriate solutions can help ensure that images are displayed correctly across various platforms. Here is a PHP code snippet that allows you to rotate an image based on its EXIF orientation data, using the GD library in PHP.

Source code viewer
  1. function exif_orientation_rotate($file_path, $file_mime) {
  2. if (function_exists('exif_read_data') && $file_mime == 'image/jpeg') {
  3. $file_exif = @exif_read_data($file_path);
  4.  
  5. // Ensure that the Orientation key|value exists, otherwise leave.
  6. if (!is_array($file_exif) || !isset($file_exif['Orientation'])) {
  7. return;
  8. }
  9. // Orientation numbers and corresponding degrees.
  10. // @note: Odd numbers are flipped images, would need different process.
  11. switch ($file_exif['Orientation']) {
  12. case 3:
  13. $degrees = 180;
  14. break;
  15. case 6:
  16. $degrees = 90;
  17. break;
  18. case 8:
  19. $degrees = 270;
  20. break;
  21. default:
  22. $degrees = 0;
  23. }
  24.  
  25. if ($degrees > 0) {
  26. // Load the image object for manipulation.
  27. $file_image = image_load($file_path);
  28.  
  29. if (image_rotate($file_image, $degrees, 0xffffff)) {
  30. image_save($file_image);
  31. }
  32. }
  33. }
  34. }
Programming Language: PHP