private function _saveAsWebp($imageInstance, $path, $sourceExtension, $saveOptions)
{
if ($this->getSetting('useCwebp')) {
// save temp file
$tempFile = $this->_saveTemporaryFile($imageInstance, $sourceExtension);
// convert to webp with cwebp
$command = escapeshellcmd($this->getSetting('cwebpPath') . ' ' . $this->getSetting('cwebpOptions') . ' -q ' . $saveOptions['webp_quality'] . ' ' . $tempFile . ' -o ' . $path);
$r = shell_exec($command);
if (!IOHelper::fileExists($path)) {
throw new Exception(Craft::t('Save operation failed'));
}
// delete temp file
IOHelper::deleteFile($tempFile);
} else {
if ($this->imageDriver === 'gd') {
$instance = $imageInstance->getGdResource();
if (false === \imagewebp($instance, $path, $saveOptions['webp_quality'])) {
throw new Exception(Craft::t('Save operation failed'));
}
// Fix for corrupt file bug (http://stackoverflow.com/questions/30078090/imagewebp-php-creates-corrupted-webp-files)
if (filesize($path) % 2 == 1) {
file_put_contents($path, "", FILE_APPEND);
}
}
if ($this->imageDriver === 'imagick') {
$instance = $imageInstance->getImagick();
$instance->setImageFormat('webp');
$instance->setImageAlphaChannel(\Imagick::ALPHACHANNEL_ACTIVATE);
$instance->setBackgroundColor(new \ImagickPixel('transparent'));
$instance->setImageCompressionQuality($saveOptions['webp_quality']);
$imagickOptions = $saveOptions['webp_imagick_options'];
if ($imagickOptions && count($imagickOptions) > 0) {
foreach ($imagickOptions as $key => $val) {
$instance->setOption('webp:' . $key, $val);
}
}
$instance->writeImage($path);
}
}
}