You are here

FocusScaleCropImageEffect.php in Image Focus Crop 8

File

src/Plugin/ImageEffect/FocusScaleCropImageEffect.php
View source
<?php

namespace Drupal\image_focus\Plugin\ImageEffect;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Image\ImageInterface;
use Drupal\image\Plugin\ImageEffect\ResizeImageEffect;
use Drupal\image_focus\lib\ImageFocusEntropy;
use svay\FaceDetector;

/**
 * Crops with focus an image resource.
 *
 * @ImageEffect(
 *   id = "image_focus_scale_crop",
 *   label = @Translation("Focus Scale and Crop"),
 *   description = @Translation("Use Image entrophy to detect focal point")
 * )
 */
class FocusScaleCropImageEffect extends ResizeImageEffect {

  /**
   * {@inheritdoc}
   */
  public function applyEffect(ImageInterface $image) {
    $width = $this->configuration['width'];
    $height = $this->configuration['height'];
    list($cx, $cy) = $this
      ->getFocalPoint($image);
    $scale = max($width / $image
      ->getWidth(), $height / $image
      ->getHeight());
    if (!$image
      ->resize($image
      ->getWidth() * $scale, $image
      ->getHeight() * $scale)) {
      $this->logger
        ->error('Image resize failed using the %toolkit toolkit on %path (%mimetype, %dimensions)', [
        '%toolkit' => $image
          ->getToolkitId(),
        '%path' => $image
          ->getSource(),
        '%mimetype' => $image
          ->getMimeType(),
        '%dimensions' => $image
          ->getWidth() . 'x' . $image
          ->getHeight(),
      ]);
      return FALSE;
    }
    $x = max(0, min($image
      ->getWidth() - $width, $cx * $scale - $width / 2));
    $y = max(0, min($image
      ->getHeight() - $height, $cy * $scale - $height / 2));
    if (!$image
      ->crop($x, $y, $width, $height)) {
      $this->logger
        ->error('Image crop failed using the %toolkit toolkit on %path (%mimetype, %dimensions)', [
        '%toolkit' => $image
          ->getToolkitId(),
        '%path' => $image
          ->getSource(),
        '%mimetype' => $image
          ->getMimeType(),
        '%dimensions' => $image
          ->getWidth() . 'x' . $image
          ->getHeight(),
      ]);
      return FALSE;
    }
    return TRUE;
  }

  /**
   * Method getFocalPoint.
   *
   * @param \Drupal\Core\Image\ImageInterface $image
   *   Image.
   *
   * @return array
   *   Return array.
   */
  private function getFocalPoint(ImageInterface $image) {
    $extension = str_replace('jpg', 'jpeg', explode('/', $image
      ->getMimeType())[1]);
    $function = 'imagecreatefrom' . $extension;
    if (function_exists($function) && ($resource = $function($image
      ->getSource()))) {
      if ($this->configuration['face_detect']) {
        $config = \Drupal::configFactory()
          ->get('image_focus.settings');
        if ($config
          ->get('image_focus_face_detection_maxsize') * 1024 > $image
          ->getFileSize() && ($result = $this
          ->getFaceDetection($resource))) {
          return $result;
        }
      }
      if ($result = $this
        ->getImageEntropy($resource)) {
        return $result;
      }
    }
    return [
      $image
        ->getWidth() / 2,
      $image
        ->getHeight() / 2,
    ];
  }

  /**
   * Method getImageEntropy.
   *
   * @param mixed $resource
   *   Resource.
   *
   * @return array
   *   Return array.
   */
  private function getImageEntropy($resource) {
    $entropy = new ImageFocusEntropy($resource);
    return $entropy
      ->getFocalPoint();
  }

  /**
   * Get Face detection.
   *
   * @param mixed $resource
   *   Resource.
   *
   * @return array|bool
   *   Points of false.
   */
  private function getFaceDetection($resource) {
    $detector = new FaceDetector();
    $detector
      ->faceDetect($resource);
    if ($face = $detector
      ->getFace()) {
      return [
        $face['x'] + $face['w'] / 2,
        $face['y'] + $face['w'] / 2,
      ];
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function getSummary() {
    $summary = [
      '#theme' => 'image_crop_summary',
      '#data' => $this->configuration,
    ];
    $summary += parent::getSummary();
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'face_detect' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['face_detect'] = [
      '#type' => 'checkbox',
      '#title' => t('Face detect'),
      '#default_value' => $this->configuration['face_detect'],
      '#description' => t('Enable face detect to get focal point.'),
    ];
    return $form;
  }

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

}

Classes

Namesort descending Description
FocusScaleCropImageEffect Crops with focus an image resource.