diff --git a/file_entity.file.inc b/file_entity.file.inc index 9e97643..3a52ff4 100644 --- a/file_entity.file.inc +++ b/file_entity.file.inc @@ -32,6 +32,9 @@ function file_entity_file_presave($file) { field_attach_presave('file', $file); + // Provide EXIF Orientation correction. + _file_entity_exif_orientation($file); + // Fetch image dimensions. file_entity_metadata_fetch_image_dimensions($file); } @@ -317,3 +320,48 @@ function file_entity_file_metadata_info() { $info['height'] = array('label' => t('Height'), 'type' => 'integer'); return $info; } + +/** + * Rotates an image to its EXIF Orientation + * + * iPhone 4 and up save all images in landscape, relying on EXIF data to + * set the orientation properly. This doesn't always translate well in the + * browser or other devices. + * @link: http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto/ + */ +function _file_entity_exif_orientation($file) { + + if (function_exists('exif_read_data') && $file->filemime == 'image/jpeg') { + $file_exif = exif_read_data(drupal_realpath($file->uri)); + + // Ensure that the Orientation key|value exists, otherwise leave. + if (!isset($file_exif['Orientation'])) { + return; + } + // Orientation numbers and corresponding degrees. + // @note: Odd numbers are flipped images, would need different process. + $orientation_types = array( + 8 => 180, + 7 => 180, + 6 => 90, + 5 => 90, + 4 => -90, + 3 => -90, + 2 => 0, + 1 => 0, + // Just in case. + 0 => 0, + ); + + // Get the origentation rotation degrees + $degrees = $orientation_types[$file_exif['Orientation']]; + if ($degrees > 0) { + // Load the image object for manipulation + $file_image = image_load(drupal_realpath($file->uri)); + + if (image_rotate($file_image, $degrees)) { + image_save($file_image); + } + } + } +}