Created
June 14, 2017 15:25
-
-
Save lerni/0a4917cf1555c5f95c2ad0b839a1580d to your computer and use it in GitHub Desktop.
SilverStripe Imagick high quality and low file size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// smart defaults for high quality and low file size | |
// https://github.com/nwtn/php-respimg/blob/master/src/Respimg.php#L235 | |
// --- | |
// Only: | |
// classexists: 'Imagick' | |
// --- | |
// Image: | |
// backend: 'FixedImagickBackend' | |
// ImagickBackend: | |
// default_quality: 80 | |
if(class_exists('Imagick')) { | |
class FixedImagickBackend extends ImagickBackend | |
{ | |
public function smartResize($columns, $rows, $optim = false) { | |
$quality = 76; | |
if ($qualityFromConfig = Config::inst()->get('ImagickBackend','default_quality')) { | |
$quality = $qualityFromConfig; | |
} | |
$this->setOption('filter:support', '2.0'); | |
$this->thumbnailImage($columns, $rows, false, false, \Imagick::FILTER_TRIANGLE); | |
if ($optim) { | |
$this->unsharpMaskImage(0.25, 0.08, 8.3, 0.045); | |
} else { | |
$this->unsharpMaskImage(0.25, 0.25, 8, 0.065); | |
} | |
$this->posterizeImage(136, false); | |
$this->setImageCompressionQuality($quality); | |
$this->setOption('jpeg:fancy-upsampling', 'off'); | |
$this->setOption('png:compression-filter', '5'); | |
$this->setOption('png:compression-level', '9'); | |
$this->setOption('png:compression-strategy', '1'); | |
$this->setOption('png:exclude-chunk', 'all'); | |
$this->setInterlaceScheme(\Imagick::INTERLACE_NO); | |
$this->setColorspace(\Imagick::COLORSPACE_SRGB); | |
if (!$optim) { | |
$this->stripImage(); | |
} | |
} | |
public function resize($width, $height) { | |
if(!$this->valid()) return; | |
if($width < 0 || $height < 0) throw new InvalidArgumentException("Image resizing dimensions cannot be negative"); | |
if(!$width && !$height) throw new InvalidArgumentException("No dimensions given when resizing image"); | |
if(!$width) throw new InvalidArgumentException("Width not given when resizing image"); | |
if(!$height) throw new InvalidArgumentException("Height not given when resizing image"); | |
//use whole numbers, ensuring that size is at least 1x1 | |
$width = max(1, round($width)); | |
$height = max(1, round($height)); | |
$geometry = $this->getImageGeometry(); | |
// Check that a resize is actually necessary. | |
if ($width == $geometry["width"] && $height == $geometry["height"]) { | |
return $this; | |
} | |
$new = clone $this; | |
$new->smartResize($width, $height, 1, false); | |
return $new; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment