You are here

protected function BackgroundImageManager::colorSampleImagemagickImage in Background Image 8

Same name and namespace in other branches
  1. 2.x src/BackgroundImageManager.php \Drupal\background_image\BackgroundImageManager::colorSampleImagemagickImage()
  2. 2.0.x src/BackgroundImageManager.php \Drupal\background_image\BackgroundImageManager::colorSampleImagemagickImage()

Determines the average color of an image using the Imagemagick toolkit.

Due to how Imagemagick's toolkit works in Drupal, this doesn't actually use any of the methods provided by the toolkit. This is because it operates under the assumption that the output will be saved as an image.

Since this is using an external binary and requires reading the text output, the arguments must be constructed manually and the ImagemagickExecManager service must be used directly.

@noinspection PhpDocMissingThrowsInspection

Parameters

\Drupal\imagemagick\Plugin\ImageToolkit\ImagemagickToolkit $image: An Imagemagick toolkit object.

string $default: A default lowercase simple color (HEX) representation to use if unable to sample the image.

Return value

string An associative array with red, green, blue and alpha keys that contains the appropriate values for the specified color index.

See also

https://stackoverflow.com/a/25488429

1 call to BackgroundImageManager::colorSampleImagemagickImage()
BackgroundImageManager::colorSampleImage in src/BackgroundImageManager.php
Samples the average color of an image file.

File

src/BackgroundImageManager.php, line 302

Class

BackgroundImageManager

Namespace

Drupal\background_image

Code

protected function colorSampleImagemagickImage(ImagemagickToolkit $image, $default = NULL) {

  // Note: this service cannot be injected because not everyone will have
  // this module installed. It can only be accessed here via runtime.

  /** @var \Drupal\imagemagick\ImagemagickExecManagerInterface $exec_manager */
  $exec_manager = \Drupal::service('imagemagick.exec_manager');

  /** @var \Drupal\imagemagick\ImagemagickExecArguments $arguments */
  $arguments = (new \ReflectionClass('\\Drupal\\imagemagick\\ImagemagickExecArguments'))
    ->newInstance($exec_manager)
    ->setSourceLocalPath($this->fileSystem
    ->realpath($image
    ->getSource()));
  if (method_exists($arguments, 'add')) {
    $arguments
      ->add('-resize 1x1\\!')
      ->add('-format "%[fx:int(255*r+.5)],%[fx:int(255*g+.5)],%[fx:int(255*b+.5)]"')
      ->add('info:-');
  }
  else {
    $arguments
      ->addArgument('-resize 1x1\\!')
      ->addArgument('-format "%[fx:int(255*r+.5)],%[fx:int(255*g+.5)],%[fx:int(255*b+.5)]"')
      ->addArgument('info:-');
  }
  if ($exec_manager
    ->execute('convert', $arguments, $output, $error)) {
    return @Color::rgbToHex(explode(',', $output)) ?: $default;
  }
  return $default;
}