You are here

public function ImageAPIOptimizePipeline::applyToImage in Image Optimize (or ImageAPI Optimize) 4.x

Same name and namespace in other branches
  1. 8.3 src/Entity/ImageAPIOptimizePipeline.php \Drupal\imageapi_optimize\Entity\ImageAPIOptimizePipeline::applyToImage()
  2. 8.2 src/Entity/ImageAPIOptimizePipeline.php \Drupal\imageapi_optimize\Entity\ImageAPIOptimizePipeline::applyToImage()

Creates a new image derivative based on this image optimize pipeline.

Generates an image derivative applying all image optimize processors and saving the resulting image.

Parameters

string $image_uri: Original image file URI.

Return value

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

Overrides ImageAPIOptimizePipelineInterface::applyToImage

File

src/Entity/ImageAPIOptimizePipeline.php, line 168

Class

ImageAPIOptimizePipeline
Defines an image optimize pipeline configuration entity.

Namespace

Drupal\imageapi_optimize\Entity

Code

public function applyToImage($image_uri) {

  // If the source file doesn't exist, return FALSE.
  $image = \Drupal::service('image.factory')
    ->get($image_uri);
  if (!$image
    ->isValid()) {
    return FALSE;
  }

  /*
  Copy image to optimize to a temp location so that:
  1. It's always a local image.
  2. The filename is only ascii characters.
  */
  $file_extension = strtolower(substr(strrchr($image_uri, '.'), 1));
  $temp_image_uri = 'temporary://image_api_optimize_' . Crypt::randomBytesBase64(8) . '.' . $file_extension;
  foreach ($this
    ->getProcessors() as $processor) {

    // Create a copy of this image for the processor to work on.
    $temp_image_uri = \Drupal::service('file_system')
      ->copy($image_uri, $temp_image_uri, FileSystemInterface::EXISTS_RENAME);
    if ($temp_image_uri === FALSE) {
      return FALSE;
    }

    // Add the temporary file to be cleaned up later.
    $this->temporaryFiles[] = $temp_image_uri;

    // Apply the actual processor.
    $image_changed = $processor
      ->applyToImage($temp_image_uri);

    // The file may have changed on disk after each processor has been
    // applied, and PHP has a cache of file size information etc. so clear
    // it here so that later calls to filesize() etc. get the correct
    // information.
    clearstatcache();
    if ($image_changed) {

      // Copy the temporary file back over the original image.
      \Drupal::service('file_system')
        ->move($temp_image_uri, $image_uri, FileSystemInterface::EXISTS_REPLACE);
    }
  }
  return TRUE;
}