You are here

class AutoOrientImageEffect in Image Effects 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/ImageEffect/AutoOrientImageEffect.php \Drupal\image_effects\Plugin\ImageEffect\AutoOrientImageEffect
  2. 8.2 src/Plugin/ImageEffect/AutoOrientImageEffect.php \Drupal\image_effects\Plugin\ImageEffect\AutoOrientImageEffect

Automatically adjusts the orientation of an image resource.

Uses EXIF Orientation tags to determine the image orientation. EXIF: https://en.wikipedia.org/wiki/Exchangeable_image_file_format. EXIF orientation tag: http://sylvana.net/jpegcrop/exif_orientation.html.

Originally contributed to the imagecache_actions module by jonathan_hunt https://drupal.org/user/28976, September 1, 2009.

Plugin annotation


@ImageEffect(
  id = "image_effects_auto_orient",
  label = @Translation("Automatically correct orientation"),
  description = @Translation("Automatically rotates images according to orientation flag set by many phones and digital cameras.")
)

Hierarchy

Expanded class hierarchy of AutoOrientImageEffect

File

src/Plugin/ImageEffect/AutoOrientImageEffect.php, line 30

Namespace

Drupal\image_effects\Plugin\ImageEffect
View source
class AutoOrientImageEffect extends ConfigurableImageEffectBase implements ContainerFactoryPluginInterface {

  /**
   * The MIME type guessing service.
   *
   * @var \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface
   */
  protected $mimeTypeGuesser;

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  /**
   * Constructs an AutoOrientImageEffect object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesserInterface $mime_type_guesser
   *   The MIME type guessing service.
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system service.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, LoggerInterface $logger, MimeTypeGuesserInterface $mime_type_guesser, FileSystemInterface $file_system) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $logger);
    $this->mimeTypeGuesser = $mime_type_guesser;
    $this->fileSystem = $file_system;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('logger.factory')
      ->get('image'), $container
      ->get('file.mime_type.guesser'), $container
      ->get('file_system'));
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'scan_exif' => TRUE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    if (!extension_loaded('exif')) {

      // Issue a warning if the PHP EXIF extension is not enabled.
      drupal_set_message($this
        ->t('This image effect requires the PHP EXIF extension to be enabled to work properly.'), 'warning');
    }
    $form['info'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Information'),
    ];
    $form['info']['help'] = [
      '#markup' => $this
        ->t("<p>Certain cameras can embed <em>orientation</em> information into image\n        files when they save them. This information is embedded in an EXIF tag\n        and can be used to rotate images to their correct position for display.\n        <em>Not all cameras or images contain this information.</em>\n        This process is only useful for images that contain this information,\n        whereas for other images it is harmless.\n        </p>\n        <p>Although most modern browsers do support the orientation tag, the\n        information may get lost or become incorrect by other operations.\n        So, to support all browsers and prevent rotation errors, it is better to\n        start each image style with this effect.\n        </p>\n        <p>The expected/supported values are:<br/>\n        <strong>Tag</strong>: <code>0x0112  Orientation</code>\n        </p>\n        <ul>\n        <li>1 = Horizontal (normal)</li>\n        <li>3 = Rotate 180</li>\n        <li>6 = Rotate 90 CW</li>\n        <li>8 = Rotate 270 CW</li>\n        </ul>\n        <p>Wikipedia: <a href='https://en.wikipedia.org/wiki/Exchangeable_image_file_format'>Exchangeable image file format</a></p>\n      "),
    ];
    $form['scan_exif'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Scan image file'),
      '#description' => $this
        ->t('When selected, original image files supporting EXIF data (e.g. JPEG, TIFF) will be scanned to determine styled image orientation and dimensions. This slightly impacts performance, but allows to render more accurate HTML <kbd>&lt;img&gt;</kbd> tags.'),
      '#default_value' => $this->configuration['scan_exif'],
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $this->configuration['scan_exif'] = $form_state
      ->getValue('scan_exif');
  }

  /**
   * {@inheritdoc}
   */
  public function applyEffect(ImageInterface $image) {

    // Test to see if EXIF is supported by the image format.
    if (in_array($image
      ->getMimeType(), [
      'image/jpeg',
      'image/tiff',
    ])) {

      // Hand over to toolkit.
      return $image
        ->apply('auto_orient');
    }
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function transformDimensions(array &$dimensions, $uri) {

    // Test to see if EXIF is supported by the image format.
    $mime_type = $this->mimeTypeGuesser
      ->guess($uri);
    if (!in_array($mime_type, [
      'image/jpeg',
      'image/tiff',
    ])) {

      // Not an EXIF enabled image, return.
      return;
    }
    if ($dimensions['width'] && $dimensions['height'] && $this->configuration['scan_exif']) {

      // Both dimensions in input, and effect is configured to check the
      // the input file. Read EXIF data, and determine image orientation.
      if (($file_path = $this->fileSystem
        ->realpath($uri)) && function_exists('exif_read_data')) {
        if ($exif_data = @exif_read_data($file_path)) {
          $orientation = isset($exif_data['Orientation']) ? $exif_data['Orientation'] : NULL;
          if (in_array($orientation, [
            5,
            6,
            7,
            8,
          ])) {
            $tmp = $dimensions['width'];
            $dimensions['width'] = $dimensions['height'];
            $dimensions['height'] = $tmp;
          }
          return;
        }
      }
    }

    // Either no full dimensions in input, or effect is configured to skip
    // checking the input file, or EXIF extension is missing. Set both
    // dimensions to NULL.
    $dimensions['width'] = $dimensions['height'] = NULL;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AutoOrientImageEffect::$fileSystem protected property The file system service.
AutoOrientImageEffect::$mimeTypeGuesser protected property The MIME type guessing service.
AutoOrientImageEffect::applyEffect public function Applies an image effect to the image object. Overrides ImageEffectInterface::applyEffect
AutoOrientImageEffect::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
AutoOrientImageEffect::create public static function Creates an instance of the plugin. Overrides ImageEffectBase::create
AutoOrientImageEffect::defaultConfiguration public function Gets default configuration for this plugin. Overrides ImageEffectBase::defaultConfiguration
AutoOrientImageEffect::submitConfigurationForm public function Form submission handler. Overrides ConfigurableImageEffectBase::submitConfigurationForm
AutoOrientImageEffect::transformDimensions public function Determines the dimensions of the styled image. Overrides ImageEffectBase::transformDimensions
AutoOrientImageEffect::__construct public function Constructs an AutoOrientImageEffect object. Overrides ImageEffectBase::__construct
ConfigurableImageEffectBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 2
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
ImageEffectBase::$logger protected property A logger instance.
ImageEffectBase::$uuid protected property The image effect ID.
ImageEffectBase::$weight protected property The weight of the image effect.
ImageEffectBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ImageEffectBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ImageEffectBase::getDerivativeExtension public function Returns the extension of the derivative after applying this image effect. Overrides ImageEffectInterface::getDerivativeExtension 1
ImageEffectBase::getSummary public function Returns a render array summarizing the configuration of the image effect. Overrides ImageEffectInterface::getSummary 3
ImageEffectBase::getUuid public function Returns the unique ID representing the image effect. Overrides ImageEffectInterface::getUuid
ImageEffectBase::getWeight public function Returns the weight of the image effect. Overrides ImageEffectInterface::getWeight
ImageEffectBase::label public function Returns the image effect label. Overrides ImageEffectInterface::label
ImageEffectBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ImageEffectBase::setWeight public function Sets the weight for this image effect. Overrides ImageEffectInterface::setWeight
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.