You are here

class WatermarkImageEffect in Image Effects 8

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

Class WatermarkImageEffect.

Plugin annotation


@ImageEffect(
  id = "image_effects_watermark",
  label = @Translation("Watermark"),
  description = @Translation("Add watermark image effect.")
)

Hierarchy

Expanded class hierarchy of WatermarkImageEffect

File

src/Plugin/ImageEffect/WatermarkImageEffect.php, line 24

Namespace

Drupal\image_effects\Plugin\ImageEffect
View source
class WatermarkImageEffect extends ConfigurableImageEffectBase implements ContainerFactoryPluginInterface {
  use AnchorTrait;

  /**
   * The image factory service.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  /**
   * The image selector plugin.
   *
   * @var \Drupal\image_effects\Plugin\ImageEffectsPluginBaseInterface
   */
  protected $imageSelector;

  /**
   * Constructs an WatermarkImageEffect 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 \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory service.
   * @param \Drupal\image_effects\Plugin\ImageEffectsPluginBaseInterface $image_selector
   *   The image selector plugin.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, LoggerInterface $logger, ImageFactory $image_factory, ImageEffectsPluginBaseInterface $image_selector) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $logger);
    $this->imageFactory = $image_factory;
    $this->imageSelector = $image_selector;
  }

  /**
   * {@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('image.factory'), $container
      ->get('plugin.manager.image_effects.image_selector')
      ->getPlugin());
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'watermark_image' => '',
      'watermark_width' => NULL,
      'watermark_height' => NULL,
      'placement' => 'center-center',
      'x_offset' => 0,
      'y_offset' => 0,
      'opacity' => 100,
    ] + parent::defaultConfiguration();
  }

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

    // Get the human readable label for placement.
    $summary['#data']['placement'] = $this
      ->anchorOptions()[$summary['#data']['placement']];
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $options = [
      '#title' => $this
        ->t('Watermark image'),
      '#description' => $this
        ->t('Image to use as watermark.'),
      '#default_value' => $this->configuration['watermark_image'],
    ];
    $form['watermark_image'] = $this->imageSelector
      ->selectionElement($options);
    $form['watermark_resize'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Watermark resize'),
      '#description' => $this
        ->t('Select dimensions either in pixels or as percentage of the <strong>current canvas</strong>. Leaving one dimension empty will resize the watermark maintaing its aspect ratio. Leave both dimensions empty to apply the watermark in its original dimensions.'),
      '#open' => TRUE,
    ];
    $form['watermark_resize']['watermark_width'] = [
      '#type' => 'image_effects_px_perc',
      '#title' => $this
        ->t('Watermark width'),
      '#default_value' => $this->configuration['watermark_width'],
      '#size' => 5,
      '#maxlength' => 5,
      '#required' => FALSE,
    ];
    $form['watermark_resize']['watermark_height'] = [
      '#type' => 'image_effects_px_perc',
      '#title' => $this
        ->t('Watermark height'),
      '#default_value' => $this->configuration['watermark_height'],
      '#size' => 5,
      '#maxlength' => 5,
      '#required' => FALSE,
    ];
    $form['placement'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Placement'),
      '#options' => $this
        ->anchorOptions(),
      '#theme' => 'image_anchor',
      '#default_value' => $this->configuration['placement'],
      '#description' => $this
        ->t('Position of the watermark on the canvas.'),
    ];
    $form['x_offset'] = [
      '#type' => 'image_effects_px_perc',
      '#title' => $this
        ->t('Horizontal offset'),
      '#description' => $this
        ->t("Additional horizontal offset from placement. Enter a value, and specify if pixels or percent of the canvas width. '+' or no sign shifts the watermark rightward, '-' sign leftward."),
      '#default_value' => $this->configuration['x_offset'],
      '#maxlength' => 4,
      '#size' => 4,
    ];
    $form['y_offset'] = [
      '#type' => 'image_effects_px_perc',
      '#title' => $this
        ->t('Vertical offset'),
      '#description' => $this
        ->t("Additional vertical offset from placement. Enter a value, and specify if pixels or percent of the canvas height. '+' or no sign shifts the watermark downward, '-' sign upward."),
      '#default_value' => $this->configuration['y_offset'],
      '#maxlength' => 4,
      '#size' => 4,
    ];
    $form['opacity'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Opacity'),
      '#field_suffix' => '%',
      '#description' => $this
        ->t('Opacity, in percentage, of the watermark on the canvas. 0% is fully transparent, 100% is fully opaque.'),
      '#default_value' => $this->configuration['opacity'],
      '#min' => 0,
      '#max' => 100,
      '#maxlength' => 3,
      '#size' => 3,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::submitConfigurationForm($form, $form_state);
    $this->configuration['watermark_image'] = $form_state
      ->getValue('watermark_image');
    $this->configuration['watermark_width'] = $form_state
      ->getValue([
      'watermark_resize',
      'watermark_width',
    ]);
    $this->configuration['watermark_height'] = $form_state
      ->getValue([
      'watermark_resize',
      'watermark_height',
    ]);
    $this->configuration['placement'] = $form_state
      ->getValue('placement');
    $this->configuration['x_offset'] = $form_state
      ->getValue('x_offset');
    $this->configuration['y_offset'] = $form_state
      ->getValue('y_offset');
    $this->configuration['opacity'] = $form_state
      ->getValue('opacity');
  }

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

    // Get the watermark image object.
    $watermark_image = $this->imageFactory
      ->get($this->configuration['watermark_image']);
    if (!$watermark_image
      ->isValid()) {
      $this->logger
        ->error('Image watermark failed using the %toolkit toolkit on %path', [
        '%toolkit' => $image
          ->getToolkitId(),
        '%path' => $this->configuration['watermark_image'],
      ]);
      return FALSE;
    }

    // Determine watermark dimensions if they need to be changed.
    if ((bool) $this->configuration['watermark_width'] || (bool) $this->configuration['watermark_height']) {
      $watermark_aspect = $watermark_image
        ->getHeight() / $watermark_image
        ->getWidth();
      $watermark_width = ImageUtility::percentFilter($this->configuration['watermark_width'], $image
        ->getWidth());
      $watermark_height = ImageUtility::percentFilter($this->configuration['watermark_height'], $image
        ->getHeight());
      if ($watermark_width && !$watermark_height) {
        $watermark_height = (int) round($watermark_width * $watermark_aspect);
      }
      elseif (!$watermark_width && $watermark_height) {
        $watermark_width = (int) round($watermark_height / $watermark_aspect);
      }
    }
    else {
      $watermark_width = $watermark_image
        ->getWidth();
      $watermark_height = $watermark_image
        ->getHeight();
    }

    // Calculate position of watermark on source image based on placement
    // option.
    list($x, $y) = explode('-', $this->configuration['placement']);
    $x_pos = round(image_filter_keyword($x, $image
      ->getWidth(), $watermark_width));
    $y_pos = round(image_filter_keyword($y, $image
      ->getHeight(), $watermark_height));

    // Calculate offset based on px/percentage.
    $x_offset = (int) ImageUtility::percentFilter($this->configuration['x_offset'], $image
      ->getWidth());
    $y_offset = (int) ImageUtility::percentFilter($this->configuration['y_offset'], $image
      ->getHeight());
    return $image
      ->apply('watermark', [
      'watermark_image' => $watermark_image,
      'watermark_width' => $watermark_width !== $watermark_image
        ->getWidth() ? $watermark_width : NULL,
      'watermark_height' => $watermark_height !== $watermark_image
        ->getHeight() ? $watermark_height : NULL,
      'x_offset' => $x_pos + $x_offset,
      'y_offset' => $y_pos + $y_offset,
      'opacity' => $this->configuration['opacity'],
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AnchorTrait::anchorOptions protected function Returns an array of options for anchoring an image.
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::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
ImageEffectBase::transformDimensions public function Determines the dimensions of the styled image. Overrides ImageEffectInterface::transformDimensions 4
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.
WatermarkImageEffect::$imageFactory protected property The image factory service.
WatermarkImageEffect::$imageSelector protected property The image selector plugin.
WatermarkImageEffect::applyEffect public function Applies an image effect to the image object. Overrides ImageEffectInterface::applyEffect
WatermarkImageEffect::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
WatermarkImageEffect::create public static function Creates an instance of the plugin. Overrides ImageEffectBase::create
WatermarkImageEffect::defaultConfiguration public function Gets default configuration for this plugin. Overrides ImageEffectBase::defaultConfiguration
WatermarkImageEffect::getSummary public function Returns a render array summarizing the configuration of the image effect. Overrides ImageEffectBase::getSummary
WatermarkImageEffect::submitConfigurationForm public function Form submission handler. Overrides ConfigurableImageEffectBase::submitConfigurationForm
WatermarkImageEffect::__construct public function Constructs an WatermarkImageEffect object. Overrides ImageEffectBase::__construct