public function save($path, $format = null, $quality = null)
{
if (!$format) {
$format = "png32";
}
$format = strtolower($format);
if ($format == "png") {
// we need to force imagick to create png32 images, otherwise this can cause some strange effects
// when used with gray-scale images
$format = "png32";
}
if ($format == "original") {
$format = strtolower($this->resource->getImageFormat());
}
$originalFilename = null;
if (!$this->reinitializing) {
if ($this->getUseContentOptimizedFormat()) {
$format = "jpeg";
if ($this->hasAlphaChannel()) {
$format = "png32";
}
}
}
$i = $this->resource;
// this is because of HHVM which has problems with $this->resource->writeImage();
if (in_array($format, ["jpeg", "pjpeg", "jpg"]) && $this->isAlphaPossible) {
// set white background for transparent pixels
$i->setImageBackgroundColor("#ffffff");
// Imagick version compatibility
$alphaChannel = 11;
// This works at least as far back as version 3.1.0~rc1-1
if (defined("Imagick::ALPHACHANNEL_REMOVE")) {
// Imagick::ALPHACHANNEL_REMOVE has been added in 3.2.0b2
$alphaChannel = \Imagick::ALPHACHANNEL_REMOVE;
}
$i->setImageAlphaChannel($alphaChannel);
$i->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
}
if (!$this->isPreserveMetaData()) {
$i->stripImage();
}
if (!$this->isPreserveColor()) {
$i->profileImage('*', null);
}
$i->setImageFormat($format);
if ($quality && !$this->isPreserveColor()) {
$i->setCompressionQuality((int) $quality);
$i->setImageCompressionQuality((int) $quality);
}
if ($format == "tiff") {
$i->setCompression(\Imagick::COMPRESSION_LZW);
}
// force progressive JPEG if filesize >= 10k
// normally jpeg images are bigger than 10k so we avoid the double compression (baseline => filesize check => if necessary progressive)
// and check the dimensions here instead to faster generate the image
// progressive JPEG - better compression, smaller filesize, especially for web optimization
if ($format == "jpeg" && !$this->isPreserveColor()) {
if ($this->getWidth() * $this->getHeight() > 35000) {
$i->setInterlaceScheme(\Imagick::INTERLACE_PLANE);
}
}
// Imagick isn't able to work with custom stream wrappers, so we make a workaround
$realTargetPath = null;
if (!stream_is_local($path)) {
$realTargetPath = $path;
$path = PIMCORE_SYSTEM_TEMP_DIRECTORY . "/imagick-tmp-" . uniqid() . "." . File::getFileExtension($path);
}
if (defined("HHVM_VERSION")) {
$success = $i->writeImage($path);
} else {
$success = $i->writeImage($format . ":" . $path);
}
if (!$success) {
throw new \Exception("Unable to write image: ", $path);
}
if ($realTargetPath) {
File::rename($path, $realTargetPath);
}
return $this;
}