You are here

class BackgroundImageEffect in Image Effects 8

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

Class BackgroundImageEffect.

Plugin annotation


@ImageEffect(
  id = "image_effects_background",
  label = @Translation("Background"),
  description = @Translation("Places the source image anywhere over a selected background image.")
)

Hierarchy

Expanded class hierarchy of BackgroundImageEffect

File

src/Plugin/ImageEffect/BackgroundImageEffect.php, line 23

Namespace

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

  /**
   * 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 BackgroundImageEffect 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 [
      'placement' => 'center-center',
      'x_offset' => 0,
      'y_offset' => 0,
      'opacity' => 100,
      'background_image' => '',
    ] + parent::defaultConfiguration();
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $options = [
      '#title' => $this
        ->t('Background image'),
      '#description' => $this
        ->t('Image to use for background.'),
      '#default_value' => $this->configuration['background_image'],
    ];
    $form['background_image'] = $this->imageSelector
      ->selectionElement($options);
    $form['placement'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Placement'),
      '#options' => [
        'left-top' => $this
          ->t('Top left'),
        'center-top' => $this
          ->t('Top center'),
        'right-top' => $this
          ->t('Top right'),
        'left-center' => $this
          ->t('Center left'),
        'center-center' => $this
          ->t('Center'),
        'right-center' => $this
          ->t('Center right'),
        'left-bottom' => $this
          ->t('Bottom left'),
        'center-bottom' => $this
          ->t('Bottom center'),
        'right-bottom' => $this
          ->t('Bottom right'),
      ],
      '#theme' => 'image_anchor',
      '#default_value' => $this->configuration['placement'],
      '#description' => $this
        ->t('Position of the source image on the background image.'),
    ];
    $form['x_offset'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Horizontal offset'),
      '#field_suffix' => 'px',
      '#description' => $this
        ->t('Additional horizontal offset from placement.'),
      '#default_value' => $this->configuration['x_offset'],
      '#maxlength' => 4,
      '#size' => 4,
    ];
    $form['y_offset'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Vertical offset'),
      '#field_suffix' => 'px',
      '#description' => $this
        ->t('Additional vertical offset from placement.'),
      '#default_value' => $this->configuration['y_offset'],
      '#maxlength' => 4,
      '#size' => 4,
    ];
    $form['opacity'] = [
      '#type' => 'number',
      '#title' => $this
        ->t('Opacity'),
      '#field_suffix' => '%',
      '#description' => $this
        ->t('Opacity of the source image when overlaid on the background image, in percentage. 0% means fully transparent, 100% 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['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');
    $this->configuration['background_image'] = $form_state
      ->getValue('background_image');

    // Stores background image width and height in configuration to avoid the
    // need to fetch the image from storage in ::transformDimensions.
    $background_image = $this->imageFactory
      ->get($this->configuration['background_image']);
    $this->configuration['background_image_width'] = $background_image
      ->getWidth();
    $this->configuration['background_image_height'] = $background_image
      ->getHeight();
  }

  /**
   * {@inheritdoc}
   */
  public function applyEffect(ImageInterface $image) {
    $background_image = $this->imageFactory
      ->get($this->configuration['background_image']);
    if (!$background_image
      ->isValid()) {
      $this->logger
        ->error('Image background failed using the %toolkit toolkit on %path', [
        '%toolkit' => $image
          ->getToolkitId(),
        '%path' => $this->configuration['background_image'],
      ]);
      return FALSE;
    }
    list($x, $y) = explode('-', $this->configuration['placement']);
    $x_pos = image_filter_keyword($x, $background_image
      ->getWidth(), $image
      ->getWidth());
    $y_pos = image_filter_keyword($y, $background_image
      ->getHeight(), $image
      ->getHeight());
    return $image
      ->apply('background', [
      'x_offset' => $x_pos + $this->configuration['x_offset'],
      'y_offset' => $y_pos + $this->configuration['y_offset'],
      'opacity' => $this->configuration['opacity'],
      'background_image' => $background_image,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function transformDimensions(array &$dimensions, $uri) {
    $dimensions['width'] = $this->configuration['background_image_width'];
    $dimensions['height'] = $this->configuration['background_image_height'];
  }

}

Members

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