function ColorizeImageEffect::applyEffect

Applies an image effect to the image object.

Parameters

\Drupal\Core\Image\ImageInterface $image: An image file object.

Return value

bool TRUE on success. FALSE if unable to perform the image effect on the image.

Overrides ImageEffectInterface::applyEffect

File

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

Class

ColorizeImageEffect
Colorizes an image resource.

Namespace

Drupal\image_example\Plugin\ImageEffect

Code

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;
}