You are here

public function WebP::applyToImage in ImageAPI Optimize WebP 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/ImageAPIOptimizeProcessor/WebP.php \Drupal\imageapi_optimize_webp\Plugin\ImageAPIOptimizeProcessor\WebP::applyToImage()

Apply this image optimize processor to the given image.

Image processors should modify the file in-place or overwrite the file on disk with an optimized version.

Parameters

string $image_uri: Original image file URI.

Return value

bool TRUE if an optimized image was generated, or FALSE if the image could not be optimized.

Overrides ImageAPIOptimizeProcessorInterface::applyToImage

File

src/Plugin/ImageAPIOptimizeProcessor/WebP.php, line 20

Class

WebP
Plugin annotation @ImageAPIOptimizeProcessor( id = "imageapi_optimize_webp", label = @Translation("WebP Deriver"), description = @Translation("Clone image to WebP") )

Namespace

Drupal\imageapi_optimize_webp\Plugin\ImageAPIOptimizeProcessor

Code

public function applyToImage($image_uri) {
  $source_image = $this->imageFactory
    ->get($image_uri, 'gd');
  if ($source_image) {
    $destination = $image_uri . '.webp';

    // @todo: Add try/catch.
    imagewebp($source_image
      ->getToolkit()
      ->getResource(), $destination, $this->configuration['quality']);

    // Fix issue where sometimes image fails to generate.
    if (filesize($destination) % 2 == 1) {
      file_put_contents($destination, "\0", FILE_APPEND);
    }
    return TRUE;
  }
  return FALSE;
}