You are here

public function PngQuant::applyToImage in Image Optimize Binaries 8

Overrides ImageAPIOptimizeProcessorBinaryBase::applyToImage

File

src/Plugin/ImageAPIOptimizeProcessor/PngQuant.php, line 29

Class

PngQuant
Uses the PngQuant binary to optimize images.

Namespace

Drupal\imageapi_optimize_binaries\Plugin\ImageAPIOptimizeProcessor

Code

public function applyToImage($image_uri) {
  if ($cmd = $this
    ->getFullPathToBinary()) {
    if ($this
      ->getMimeType($image_uri) === 'image/png') {
      $destination_filename = $this
        ->sanitizeFilename($image_uri);
      $options = [
        '--force',
      ];
      if (!empty($this->configuration['quality'])) {

        // Ensure that we send in any missing values.
        $quality = array_filter($this->configuration['quality']) + [
          'min' => 0,
          'max' => 100,
        ];
        $options[] = '--quality=' . escapeshellarg($quality['min'] . '-' . $quality['max']);
      }
      if (!empty($this->configuration['speed'])) {
        $options[] = '--speed=' . escapeshellarg($this->configuration['speed']);
      }

      // Instruct pngoptim to read the source file from stdin, which also
      // means that the compressed image will be on stdout.
      $options[] = '-';
      $arguments = [
        $destination_filename,
      ];
      $option_string = implode(' ', $options);
      $argument_string = implode(' ', array_map('escapeshellarg', $arguments));
      return $this
        ->saveCommandStdoutToFile(escapeshellarg($cmd) . ' ' . $option_string . ' < ' . $argument_string, $destination_filename);
    }
  }
  return FALSE;
}