public function ReSmushit::applyToImage in Image Optimize reSmush.it 8
Same name and namespace in other branches
- 2.x src/Plugin/ImageAPIOptimizeProcessor/ReSmushit.php \Drupal\imageapi_optimize_resmushit\Plugin\ImageAPIOptimizeProcessor\ReSmushit::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\ImageAPIOptimizeProcessorCode
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;
}