class ColorizeImageEffect

Colorizes an image resource.

Plugin annotation


@ImageEffect(
  id = "image_example_colorize",
  label = @Translation("Colorize"),
  description = @Translation("The colorize effect will first remove all color from the source image and then tint the image using the color specified.")
)

Hierarchy

Expanded class hierarchy of ColorizeImageEffect

Related topics

File

modules/image_example/src/Plugin/ImageEffect/ColorizeImageEffect.php, line 21

Namespace

Drupal\image_example\Plugin\ImageEffect
View source
class ColorizeImageEffect extends ConfigurableImageEffectBase {
  
  /**
   * {@inheritdoc}
   */
  public function applyEffect(ImageInterface $image) {
    $data = $this->configuration;
    // Verify that Drupal is using the PHP GD library for image manipulations
    // since this effect depends on functions implemented by the GD extension.
    if ($image->getToolkitId() != 'gd') {
      $this->logger
        ->info('Image colorize failed on %file. The image does not use the GD toolkit.', [
        '%file' => $image->getSource(),
      ]);
      return FALSE;
    }
    // phpcs:disable Drupal.Commenting.InlineComment.InvalidEndChar
    // Not all GD installations are created equal. It is a good idea to check
    // for the existence of image manipulation functions before using them.
    // PHP installations using non-bundled GD do not have imagefilter(). See the
    // @link http://www.php.net/manual/en/book.image.php PHP manual @endlink for
    // more information about image manipulation functions.
    // phpcs:enable
    if (!function_exists('imagefilter')) {
      $this->logger
        ->error('The image %image could not be colorized because the imagefilter() function is not available in this PHP installation.', [
        '%file' => $image->getSource(),
      ]);
      return FALSE;
    }
    if (!Color::validateHex($data['color'])) {
      // Use the default value, if the stored value is invalid.
      $data['color'] = '#FF6633';
    }
    $rgb = Color::hexToRgb($data['color']);
    // $source contains the \GdImage instance passed to GD functions.
    // This line only works with the GD toolkit implemented by Drupal core.
    // Other toolkits could not implement getImage(), or that method could
    // return a different value.
    $source = $image->getToolkit()
      ->getImage();
    // First desaturate the image, and then apply the new color.
    imagefilter($source, IMG_FILTER_GRAYSCALE);
    imagefilter($source, IMG_FILTER_COLORIZE, $rgb['red'], $rgb['green'], $rgb['blue']);
    return TRUE;
  }
  
  /**
   * {@inheritdoc}
   */
  public function getSummary() {
    if (Color::validateHex($this->configuration['color'])) {
      $color = $this->configuration['color'];
    }
    else {
      // Use the default value, if the stored value is invalid.
      $color = '#FF6633';
    }
    $summary = [
      '#markup' => $color,
    ];
    $summary += parent::getSummary();
    return $summary;
  }
  
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'color' => '#FF6633',
    ];
  }
  
  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    // You do not need to worry about saving/updating/deleting the collected
    // data. The Image module will automatically serialize and store all the
    // data associated with an effect.
    $form['color'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Color'),
      '#description' => $this->t('The color to use when colorizing the image. Use web-style hex colors, for example %long-value, or %short-value.', [
        '%long-value' => '#FF6633',
        '%short-value' => 'F63',
      ]),
      '#default_value' => $this->configuration['color'] ?? '',
      '#size' => 7,
      '#max_length' => 7,
      '#required' => TRUE,
    ];
    return $form;
  }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
ColorizeImageEffect::applyEffect public function Applies an image effect to the image object. Overrides ImageEffectInterface::applyEffect
ColorizeImageEffect::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
ColorizeImageEffect::defaultConfiguration public function Gets default configuration for this plugin. Overrides ImageEffectBase::defaultConfiguration
ColorizeImageEffect::getSummary public function Returns a render array summarizing the configuration of the image effect. Overrides ImageEffectBase::getSummary
ConfigurableImageEffectBase::submitConfigurationForm public function 4
ConfigurableImageEffectBase::validateConfigurationForm public function 2
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
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::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
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
ImageEffectBase::__construct public function
MessengerTrait::$messenger protected property The messenger. 16
MessengerTrait::messenger public function Gets the messenger. 16
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin.
PluginBase::$pluginDefinition protected property The plugin implementation definition.
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
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. 3
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.