You are here

function imagemagick_imagemagick_arguments_alter in ImageMagick 8

Implements hook_imagemagick_arguments_alter().

File

./imagemagick.module, line 46
Provides ImageMagick integration.

Code

function imagemagick_imagemagick_arguments_alter(ImagemagickToolkit $toolkit, $command) {
  $config = \Drupal::config('imagemagick.settings');

  // Add prepended arguments if needed.
  if ($prepend = $config
    ->get('prepend')) {
    $toolkit
      ->prependArgument($prepend);
  }
  if ($command == 'convert') {

    // Convert destination image URI to filepath.
    $local_path = $toolkit
      ->getDestinationLocalPath();
    if (empty($local_path)) {
      $destination = $toolkit
        ->getDestination();
      if (!file_valid_uri($destination)) {

        // The value of $destination is likely a file path already.
        $toolkit
          ->setDestinationLocalPath($destination);
      }
      else {

        // If we can resolve the realpath of the file, then the file is local
        // and we can assign its real path.
        $file_system = \Drupal::service('file_system');
        $path = $file_system
          ->realpath($destination);
        if ($path) {
          $toolkit
            ->setDestinationLocalPath($path);
        }
        else {

          // We are working with a remote file, set the local destination to
          // a temp local file.
          $temp_path = $file_system
            ->tempnam('temporary://', 'imagemagick_');
          $file_system
            ->unlink($temp_path);
          $temp_path .= '.' . pathinfo($destination, PATHINFO_EXTENSION);
          $toolkit
            ->setDestinationLocalPath($file_system
            ->realpath($temp_path));
        }
      }
    }

    // Change image density.
    if ($toolkit
      ->findArgument('-density') === FALSE && ($density = (int) $config
      ->get('advanced.density'))) {
      $toolkit
        ->addArgument("-density {$density} -units PixelsPerInch");
    }

    // Apply color profile.
    if ($profile = $config
      ->get('advanced.profile')) {
      if (file_exists($profile)) {
        $toolkit
          ->addArgument('-profile ' . $toolkit
          ->escapeShellArg($profile));
      }
    }
    elseif ($colorspace = $config
      ->get('advanced.colorspace')) {

      // Do not hi-jack settings made by effects.
      if ($toolkit
        ->findArgument('-colorspace') === FALSE) {
        $toolkit
          ->addArgument('-colorspace ' . $toolkit
          ->escapeShellArg($colorspace));
      }
    }

    // Change image quality.
    if ($toolkit
      ->findArgument('-quality') === FALSE) {
      $toolkit
        ->addArgument('-quality ' . \Drupal::config('imagemagick.settings')
        ->get('quality'));
    }
  }
}