class WatermarkImageEffect in Image Effects 8
Same name and namespace in other branches
- 8.3 src/Plugin/ImageEffect/WatermarkImageEffect.php \Drupal\image_effects\Plugin\ImageEffect\WatermarkImageEffect
 - 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
- class \Drupal\Component\Plugin\PluginBase implements DerivativeInspectionInterface, PluginInspectionInterface
- class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
- class \Drupal\image\ImageEffectBase implements ContainerFactoryPluginInterface, ImageEffectInterface
- class \Drupal\image\ConfigurableImageEffectBase implements ConfigurableImageEffectInterface
- class \Drupal\image_effects\Plugin\ImageEffect\WatermarkImageEffect implements ContainerFactoryPluginInterface uses AnchorTrait
 
 
 - class \Drupal\image\ConfigurableImageEffectBase implements ConfigurableImageEffectInterface
 
 - class \Drupal\image\ImageEffectBase implements ContainerFactoryPluginInterface, ImageEffectInterface
 
 - class \Drupal\Core\Plugin\PluginBase uses DependencySerializationTrait, MessengerTrait, StringTranslationTrait
 
Expanded class hierarchy of WatermarkImageEffect
File
- src/
Plugin/ ImageEffect/ WatermarkImageEffect.php, line 24  
Namespace
Drupal\image_effects\Plugin\ImageEffectView 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
| 
            Name | 
                  Modifiers | Type | Description | Overrides | 
|---|---|---|---|---|
| 
            AnchorTrait:: | 
                  protected | function | Returns an array of options for anchoring an image. | |
| 
            ConfigurableImageEffectBase:: | 
                  public | function | 
            Form validation handler. Overrides PluginFormInterface:: | 
                  2 | 
| 
            DependencySerializationTrait:: | 
                  protected | property | An array of entity type IDs keyed by the property name of their storages. | |
| 
            DependencySerializationTrait:: | 
                  protected | property | An array of service IDs keyed by property name used for serialization. | |
| 
            DependencySerializationTrait:: | 
                  public | function | 1 | |
| 
            DependencySerializationTrait:: | 
                  public | function | 2 | |
| 
            ImageEffectBase:: | 
                  protected | property | A logger instance. | |
| 
            ImageEffectBase:: | 
                  protected | property | The image effect ID. | |
| 
            ImageEffectBase:: | 
                  protected | property | The weight of the image effect. | |
| 
            ImageEffectBase:: | 
                  public | function | 
            Calculates dependencies for the configured plugin. Overrides DependentPluginInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Gets this plugin's configuration. Overrides ConfigurableInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Returns the extension of the derivative after applying this image effect. Overrides ImageEffectInterface:: | 
                  1 | 
| 
            ImageEffectBase:: | 
                  public | function | 
            Returns the unique ID representing the image effect. Overrides ImageEffectInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Returns the weight of the image effect. Overrides ImageEffectInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Returns the image effect label. Overrides ImageEffectInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Sets the configuration for this plugin instance. Overrides ConfigurableInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Sets the weight for this image effect. Overrides ImageEffectInterface:: | 
                  |
| 
            ImageEffectBase:: | 
                  public | function | 
            Determines the dimensions of the styled image. Overrides ImageEffectInterface:: | 
                  4 | 
| 
            MessengerTrait:: | 
                  protected | property | The messenger. | 29 | 
| 
            MessengerTrait:: | 
                  public | function | Gets the messenger. | 29 | 
| 
            MessengerTrait:: | 
                  public | function | Sets the messenger. | |
| 
            PluginBase:: | 
                  protected | property | Configuration information passed into the plugin. | 1 | 
| 
            PluginBase:: | 
                  protected | property | The plugin implementation definition. | 1 | 
| 
            PluginBase:: | 
                  protected | property | The plugin_id. | |
| 
            PluginBase:: | 
                  constant | A string which is used to separate base plugin IDs from the derivative ID. | ||
| 
            PluginBase:: | 
                  public | function | 
            Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface:: | 
                  |
| 
            PluginBase:: | 
                  public | function | 
            Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface:: | 
                  |
| 
            PluginBase:: | 
                  public | function | 
            Gets the definition of the plugin implementation. Overrides PluginInspectionInterface:: | 
                  3 | 
| 
            PluginBase:: | 
                  public | function | 
            Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface:: | 
                  |
| 
            PluginBase:: | 
                  public | function | Determines if the plugin is configurable. | |
| 
            StringTranslationTrait:: | 
                  protected | property | The string translation service. | 1 | 
| 
            StringTranslationTrait:: | 
                  protected | function | Formats a string containing a count of items. | |
| 
            StringTranslationTrait:: | 
                  protected | function | Returns the number of plurals supported by a given language. | |
| 
            StringTranslationTrait:: | 
                  protected | function | Gets the string translation service. | |
| 
            StringTranslationTrait:: | 
                  public | function | Sets the string translation service to use. | 2 | 
| 
            StringTranslationTrait:: | 
                  protected | function | Translates a string to the current language or to a given language. | |
| 
            WatermarkImageEffect:: | 
                  protected | property | The image factory service. | |
| 
            WatermarkImageEffect:: | 
                  protected | property | The image selector plugin. | |
| 
            WatermarkImageEffect:: | 
                  public | function | 
            Applies an image effect to the image object. Overrides ImageEffectInterface:: | 
                  |
| 
            WatermarkImageEffect:: | 
                  public | function | 
            Form constructor. Overrides PluginFormInterface:: | 
                  |
| 
            WatermarkImageEffect:: | 
                  public static | function | 
            Creates an instance of the plugin. Overrides ImageEffectBase:: | 
                  |
| 
            WatermarkImageEffect:: | 
                  public | function | 
            Gets default configuration for this plugin. Overrides ImageEffectBase:: | 
                  |
| 
            WatermarkImageEffect:: | 
                  public | function | 
            Returns a render array summarizing the configuration of the image effect. Overrides ImageEffectBase:: | 
                  |
| 
            WatermarkImageEffect:: | 
                  public | function | 
            Form submission handler. Overrides ConfigurableImageEffectBase:: | 
                  |
| 
            WatermarkImageEffect:: | 
                  public | function | 
            Constructs an WatermarkImageEffect object. Overrides ImageEffectBase:: |