The module doesn't work with Imagick toolkit

Created on 17 July 2017, over 7 years ago
Updated 5 June 2023, over 1 year ago

Tried to use the module with Imagick toolkit (and Image Widget Crop - not sure if it's relevant), discovered that the image is rotated multiple times before it is finally stored (in the original image the building was lying on its left side, when uploaded to site it was lying on its right side).
Discovered two reasons for that:
1. The module uses hook_file_presave (as opposed to hook_file_insert), so the image is processed every time it is [re]saved for whatever reason. In my configuration it was apparently saved two times.
2. As Imagick toolkit doesn't strip the EXIF (unlike GD) and the rotate() operation doesn't reset the Orientation flag in the EXIF, the image will be rotated as many times as it is saved.
Solution:
1. If using Imagick toolkit, use its "autorotate" operaton instead of generic rotate(). In that case you don't need to call exif_read_data() to determine whether the image needs rotating and how many degrees - the toolkit will do it automagically AND it will reset the Orientation flag in the EXIF so that the image won't be autorotated ever again.
2. Use hook_file_insert instead of hook_file_presave. With (1) implemented the image will not be rotated twice anyway, but why call the toolkit many times when it should only be called once.
Here's the code I wound up with for my particular case:

/**
 * Implements hook_file_insert().
 * Rotates an image to its EXIF Orientation.
 * ONLY WORKS WITH IMAGICK TOOLKIT!
 */
function HOOK_file_insert(EntityInterface $file) {
  if ($file->getMimeType() == 'image/jpeg') {
    $image = \Drupal::service('image.factory')->get($file->getFileUri());
    if ($image->getToolkit()->apply("autorotate")) {
      $image->save();
    }
  }
}

Hope this helps someone. Maybe someone will be willing to make a patch that would query the toolkit used and use different code for different toolkits - I'm a bit out of my depth here.

πŸ› Bug report
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡·πŸ‡ΊRussia marassa Moscow

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024