You are here

public function ReSmushit::applyToImage in Image Optimize reSmush.it 2.x

Same name and namespace in other branches
  1. 8 src/Plugin/ImageAPIOptimizeProcessor/ReSmushit.php \Drupal\imageapi_optimize_resmushit\Plugin\ImageAPIOptimizeProcessor\ReSmushit::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/ReSmushit.php, line 58

Class

ReSmushit
Uses the resmush.it webservice to optimize an image.

Namespace

Drupal\imageapi_optimize_resmushit\Plugin\ImageAPIOptimizeProcessor

Code

public function applyToImage($image_uri) {

  // Need to send the file off to the remote service and await a response.
  $fields[] = [
    'name' => 'files',
    'contents' => fopen($image_uri, 'r'),
  ];
  if (!empty($this->configuration['quality'])) {
    $fields[] = [
      'name' => 'qlty',
      'contents' => $this->configuration['quality'],
    ];
  }
  try {
    $response = $this->httpClient
      ->post('http://api.resmush.it/ws.php', [
      'multipart' => $fields,
    ]);
    $body = $response
      ->getBody();
    $json = json_decode($body);

    // If this has worked, we should get a dest entry in the JSON returned.
    if (isset($json->dest)) {

      // Now go fetch that, and save it locally.
      $smushedFile = $this->httpClient
        ->get($json->dest);
      if ($smushedFile
        ->getStatusCode() == 200) {
        \Drupal::service('file_system')
          ->saveData($smushedFile
          ->getBody(), $image_uri, FileSystemInterface::EXISTS_REPLACE);
        return TRUE;
      }
    }
  } catch (RequestException $e) {
    $this->logger
      ->error('Failed to download optimize image using reSmush.it due to "%error".', [
      '%error' => $e
        ->getMessage(),
    ]);
  }
  return FALSE;
}