/** * Saves the image to a file * * @param $filename string the name of the file to write to * * @return bool|PEAR_Error TRUE or a PEAR_Error object on error * @access public */ function save($filename, $type = '', $quality = null) { $options = is_array($quality) ? $quality : array(); if (is_numeric($quality)) { $options['quality'] = $quality; } $quality = $this->_getOption('quality', $options, 75); // PIMCORE_MODIFICATION $this->imagick->setCompressionQuality($quality); $this->imagick->setImageCompressionQuality($quality); if ($type && strcasecmp($type, $this->type)) { try { $this->imagick->setImageFormat($type); } catch (ImagickException $e) { return $this->raiseError('Could not save image to file (conversion failed).', IMAGE_TRANSFORM_ERROR_FAILED); } } try { $this->imagick->writeImage($filename); } catch (ImagickException $e) { return $this->raiseError('Could not save image to file: ' . $e->getMessage(), IMAGE_TRANSFORM_ERROR_IO); } if (!$this->keep_settings_on_save) { $this->free(); } return true; }
/** * @return string * @throws CM_Exception */ public function getBlob() { $this->_imagick->setImageCompressionQuality($this->getCompressionQuality()); try { if ($this->_getAnimationRequired($this->getFormat())) { $imageBlob = $this->_imagick->getImagesBlob(); } else { $imageBlob = $this->_imagick->getImageBlob(); } } catch (ImagickException $e) { throw new CM_Exception('Cannot get image blob', null, ['originalExceptionMessage' => $e->getMessage()]); } return $imageBlob; }
/** * Generates a new jpg image with new sizes from an already existing file. * (This will also work on raw files, but it will be exceptionally * slower than extracting the preview). * * @param string $sourceFilePath the path to the original file * @param string $targetFilePath the path to the target file * @param int $width the max width * @param int $height the max height of the image * @param int $quality the quality of the new image (0-100) * * @throws \InvalidArgumentException * * @return void. */ public static function generateImage($sourceFilePath, $targetFilePath, $width, $height, $quality = 60) { if (!self::checkFile($sourceFilePath)) { throw new \InvalidArgumentException('Incorrect filepath given'); } $im = new \Imagick($sourceFilePath); $im->setImageFormat('jpg'); $im->setImageCompressionQuality($quality); $im->stripImage(); $im->thumbnailImage($width, $height, true); $im->writeImage($targetFilePath); $im->clear(); $im->destroy(); }
function save($file_name = null, $quality = null) { $type = $this->out_type; if (!$type) { $type = $this->img_type; } if (!self::supportSaveType($type)) { throw new lmbImageTypeNotSupportedException($type); } $this->img->setImageFormat($type); $this->img->setImageFilename($file_name); if (!is_null($quality) && strtolower($type) == 'jpeg') { if (method_exists($this->img, 'setImageCompression')) { $this->img->setImageCompression(imagick::COMPRESSION_JPEG); $this->img->setImageCompressionQuality($quality); } else { $this->img->setCompression(imagick::COMPRESSION_JPEG); $this->img->setCompressionQuality($quality); } } if (!$this->img->writeImage($file_name)) { throw new lmbImageSaveFailedException($file_name); } $this->destroyImage(); }
/** * @param $path */ public function save($path, $format = null, $quality = null) { if (!$format) { $format = "png"; } $this->resource->stripimage(); $this->resource->setImageFormat($format); if ($quality) { $this->resource->setCompressionQuality((int) $quality); $this->resource->setImageCompressionQuality((int) $quality); } $this->resource->writeImage($path); return $this; }
/** * {@inheritdoc} */ public function save($file, $quality = 95) { // Set image quality $this->image->setImageCompressionQuality($quality); // Save image $this->image->writeImage($file); }
public function softThumb($width, $height, $path, $bg = 'transparent') { if ($this->originImage) { echo "\nWrite image to `{$path}`\n"; $resizeParams = $this->getSizes($width, $height); $overlay = clone $this->originImage; $overlay->scaleImage($resizeParams['width'], $resizeParams['height']); $overlayGeo = $overlay->getImageGeometry(); if ($overlayGeo['width'] > $overlayGeo['height']) { $resizeParams['top'] = ($height - $overlayGeo['height']) / 2; $resizeParams['left'] = 0; } else { $resizeParams['top'] = 0; $resizeParams['left'] = ($width - $overlayGeo['width']) / 2; } $thumb = new \Imagick(); $thumb->newImage($width, $height, $bg); $thumb->setImageFormat("png"); $thumb->setCompression(\Imagick::COMPRESSION_ZIP); $thumb->setImageCompressionQuality(0); $thumb->compositeImage($overlay, \Imagick::COMPOSITE_DEFAULT, $resizeParams['left'], $resizeParams['top']); $thumb->writeImageFile(fopen($path, "wb")); $thumb->destroy(); } else { throw new \Exception("As first You must load image", 404); } }
/** * Outputs the image. * * @see XenForo_Image_Abstract::output() */ public function output($outputType, $outputFile = null, $quality = 85) { $this->_image->stripImage(); // NULL means output directly switch ($outputType) { case IMAGETYPE_GIF: if (is_callable(array($this->_image, 'optimizeimagelayers'))) { $this->_image->optimizeimagelayers(); } $success = $this->_image->setImageFormat('gif'); break; case IMAGETYPE_JPEG: $success = $this->_image->setImageFormat('jpeg') && $this->_image->setImageCompression(Imagick::COMPRESSION_JPEG) && $this->_image->setImageCompressionQuality($quality); break; case IMAGETYPE_PNG: $success = $this->_image->setImageFormat('png'); break; default: throw new XenForo_Exception('Invalid output type given. Expects IMAGETYPE_XXX constant.'); } try { if ($success) { if (!$outputFile) { echo $this->_image->getImagesBlob(); } else { $success = $this->_image->writeImages($outputFile, true); } } } catch (ImagickException $e) { return false; } return $success; }
function upload_image($arr_image, $location, $compression = null, $width = 245, $height = 170) { $image_location = ""; $allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "GIF", "PNG", "pdf", "PDF"); $temp = explode(".", $arr_image["file"]["name"]); $extension = end($temp); if (($arr_image["file"]["type"] == "image/gif" || $arr_image["file"]["type"] == "image/jpeg" || $arr_image["file"]["type"] == "image/jpg" || $arr_image["file"]["type"] == "image/pjpeg" || $arr_image["file"]["type"] == "image/x-png" || $arr_image["file"]["type"] == "image/png") && $arr_image["file"]["size"] < 1024 * 1000 * 10 && in_array($extension, $allowedExts)) { if ($arr_image["file"]["error"] > 0) { echo "Return Code: " . $arr_image["file"]["error"] . "<br>"; } else { $compression_type = Imagick::COMPRESSION_JPEG; $image_location = $location . "." . $extension; if (move_uploaded_file($arr_image["file"]["tmp_name"], $image_location)) { //echo "Image Uploaded to : ".$image_location; } else { //echo "Image not uploaded"; } if (is_null($compression)) { $im = new Imagick($image_location); $im->setImageFormat('jpg'); $im->setImageCompression($compression_type); $im->setImageCompressionQuality(95); $im->stripImage(); $im->thumbnailImage($width, $height); $image_location = $location . ".jpg"; $im->writeImage($image_location); } } } return $image_location; }
/** * @param int $quality * * @throws InvalidArgumentException * * @return $this */ public function setCompressionQuality($quality = 100) { if ($quality > 100 || $quality < 1) { throw new InvalidArgumentException('Invalid compression quality value provided of %s.', null, null, (string) $quality); } $this->im->setImageCompressionQuality($quality); return $this; }
/** * Do some tricks to cleanup and minimize the thumbnails size * * @param Imagick $image */ protected function enhance(\Imagick $image) { $image->setImageCompression(\Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(75); $image->contrastImage(1); $image->adaptiveBlurImage(1, 1); $image->stripImage(); }
/** * @param int $quality 1-100 * @return $this * @throws CM_Exception_Invalid */ public function setCompressionQuality($quality) { $quality = (int) $quality; if ($quality < 1 || $quality > 100) { throw new CM_Exception_Invalid('Invalid compression quality `' . $quality . '`, should be between 1-100.'); } $this->_imagick->setImageCompressionQuality($quality); return $this; }
/** * Render the image to data string. * @param string $format * @param integer|null $quality * @return string */ protected function _render($format, $quality) { $format = $this->getFormat($format, $quality); $this->im->setFormat($format); if (isset($quality)) { $this->im->setImageCompressionQuality($quality); } return (string) $this->im; }
/** * @param \Imagick $image * @param string $format * @return \Imagick */ private function setImageFormat($image, $format) { if ($image->getImageFormat() !== $format) { $image->setImageFormat($format); } if ($format == 'jpeg') { $image->setImageCompressionQuality(90); } return $image; }
/** * 处理图片,不改变分辨率,减少图片文件大小 * @param [string] $src 原图路径 * @param [int] [图片质量] * @param [string] $dest 目标图路径 * @return [void] */ public function tinyJpeg($src, $quality = 60, $dest) { $img = new Imagick(); $img->readImage($src); $img->setImageCompression(Imagick::COMPRESSION_JPEG); $img->setImageCompressionQuality($quality); $img->stripImage(); $img->writeImage($dest); $img->clear(); }
protected function _render($type, $quality) { $type = $this->_save_function($type, $quality); $this->im->setImageCompressionQuality($quality); $this->type = $type; $this->mime = image_type_to_mime_type($type); if ($this->im->getNumberImages() > 1 && $type == "gif") { return $this->im->getImagesBlob(); } return $this->im->getImageBlob(); }
protected function _imageResizeAndSave($object) { $path = APPLICATION_ROOT . '/public_html/images/topcontentblock/'; $system->lng = $this->_getParam('lng'); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_Topcontentblock_Validator'); $msgr->addMessage('file', $adapter->getMessages(), 'title'); } if ($object->getPicture() == null) { $object->setPicture(''); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if (!$file['tmp_name']) { continue; } $path0 = $path . "253X115/"; $path1 = $path . "1263X575/"; $path2 = $path . "1263X325/"; $filename = $object->createThumbName($file['name']) . '_' . time() . '.jpg'; $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(253, 115); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(100); $image->setImageFormat('jpeg'); $image->writeImage($path0 . $filename); $image->clear(); $image->destroy(); $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(1263, 575); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(75); $image->setImageFormat('jpeg'); $image->writeImage($path1 . $filename); $image->clear(); $image->destroy(); $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(1263, 325); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(75); $image->setImageFormat('jpeg'); $image->writeImage($path2 . $filename); $image->clear(); $image->destroy(); unlink($file['tmp_name']); $object->setPicture($filename); } }
protected function _imageResizeAndSave($object) { $path = APPLICATION_ROOT . '/public_html/images/eyecatchers/'; $system->lng = $this->_getParam('lng'); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_Eyecatchers_Validator'); $msgr->addMessage('file', $adapter->getMessages(), 'title'); } if ($object->getPicture() == null) { $object->setPicture(''); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if (!$file['tmp_name']) { continue; } $path0 = $path . "253x115/"; $path1 = $path . "980x450/"; if (!is_dir($path0)) { mkdir($path0, 0777, true); } if (!is_dir($path1)) { mkdir($path1, 0777, true); } $filename = $object->createThumbName($file['name']) . '_' . time() . '.png'; $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(253, 115); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(100); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat('png32'); $image->writeImage($path0 . $filename); $image->clear(); $image->destroy(); $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(980, 450); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(75); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat('png32'); $image->writeImage($path1 . $filename); $image->clear(); $image->destroy(); unlink($file['tmp_name']); $object->setPicture($filename); } }
/** * @param Asset $asset * @return string */ public function handleSave(Asset $asset) { $newImage = new \Imagick($asset->getUploadedFile()->getRealPath()); $asset->setHeight($newImage->getImageHeight()); $asset->setWidth($newImage->getImageWidth()); /** @var array $requiredImage */ foreach ($this->requiredImages as $requiredImage) { $newImage = new \Imagick($asset->getUploadedFile()->getRealPath()); $newFilename = pathinfo($asset->getFilename(), PATHINFO_FILENAME) . '-' . $requiredImage['name'] . '.' . pathinfo($asset->getFilename(), PATHINFO_EXTENSION); $imageWidth = $newImage->getImageWidth(); $imageHeight = $newImage->getImageHeight(); $isLandscapeFormat = $imageWidth > $imageHeight; $orientation = $newImage->getImageOrientation(); $newImage->setCompression(\Imagick::COMPRESSION_JPEG); $newImage->setImageCompressionQuality($requiredImage['quality']); if ($isLandscapeFormat) { $desiredWidth = $requiredImage['long']; $newImage->resizeImage($desiredWidth, 0, \Imagick::FILTER_LANCZOS, 1); if (isset($requiredImage['short']) && boolval($requiredImage['crop']) == true) { $newImage->cropImage($desiredWidth, $requiredImage['short'], 0, 0); } else { $newImage->resizeImage(0, $requiredImage['short'], \Imagick::FILTER_LANCZOS, 1); } } else { $desiredHeight = $requiredImage['long']; $newImage->resizeImage(0, $desiredHeight, \Imagick::FILTER_LANCZOS, 1); if (isset($requiredImage['short']) && boolval($requiredImage['crop']) == true) { $newImage->cropImage($requiredImage['short'], $desiredHeight, 0, 0); } else { $newImage->resizeImage($requiredImage['short'], 0, \Imagick::FILTER_LANCZOS, 1); } } /** * This unfortunately kills the orientation. Leave EXIF-Info for now. * * $newImage->stripImage(); * $newImage->setImageOrientation($orientation); */ $this->assetStorage->uploadFile($newFilename, $newImage); $subAsset = new SubAsset(); $subAsset->setFilename($newFilename); $subAsset->setType($requiredImage['name']); $subAsset->setHeight($newImage->getImageHeight()); $subAsset->setWidth($newImage->getImageWidth()); $asset->addSubAsset($subAsset); } }
public function image($request_name, $extensions, $size, $throw = false) { $file_source = isset($_FILES[$request_name]) ? $_FILES[$request_name] : null; if ($file_source == null) { return false; } list($width, $height, $type) = getimagesize($file_source['tmp_name']); if (isset($type) && !in_array($type, self::$image_types)) { return false; } $ext = explode(".", $file_source["name"]); $file_extension = strtolower(end($ext)); if (in_array($file_extension, $extensions) == false) { return false; } if ($file_source['size'] > $size * 1024 * 1024) { return false; } $file_name = $this->getRandomName(); $destination = self::UPLOADS_DIRECTORY . '/' . $file_name . '.' . $file_extension; move_uploaded_file($file_source['tmp_name'], $destination); if ($_GET['channel'] == self::CHANNEL_APP) { $compression_type = Imagick::COMPRESSION_JPEG; $thumbnail = new Imagick($destination); $thumbnail->setImageCompression($compression_type); $thumbnail->setImageCompressionQuality(75); $thumbnail->stripImage(); $image_width = $thumbnail->getImageWidth(); $width = min($image_width, 800); $thumbnail->thumbnailImage($width, null); App_Controller_Site_Images::delete($destination); $thumbnail->writeImage($destination); } $time = date('Y-m-d H:i:s'); $ip = $_SERVER['REMOTE_ADDR']; $channel = self::CHANNEL_WEB; if (isset($_GET['channel']) && ($_GET['channel'] == self::CHANNEL_APP || $_GET['channel'] == self::CHANNEL_WEB)) { $channel = $_GET['channel']; } $query = "INSERT INTO `uploads` (`src`,`upload_time`,`token`,`ip`,`channel`) VALUES ('{$destination}','{$time}','{$file_name}','{$ip}','{$channel}')"; App_Db::getInstance()->getConn()->query($query); return $file_name; }
function imgThumbs($img) { if (file_exists($img)) { $imagen = new Imagick($img); if ($imagen->getImageHeight() <= $imagen->getImageWidth()) { $imagen->resizeImage(120, 0, Imagick::FILTER_LANCZOS, 1); } else { $imagen->resizeImage(0, 120, Imagick::FILTER_LANCZOS, 1); } $imagen->setImageCompression(Imagick::COMPRESSION_JPEG); $imagen->setImageCompressionQuality(75); $imagen->stripImage(); $imagen->writeImage($img); $imagen->destroy(); chmod($img, 0777); return true; } else { return false; } }
/** * Sets Image Compression quality on a 1-100% scale. * * @since 3.5.0 * @access public * * @param int $quality Compression Quality. Range: [1,100] * @return true|WP_Error True if set successfully; WP_Error on failure. */ public function set_quality($quality = null) { $quality_result = parent::set_quality($quality); if (is_wp_error($quality_result)) { return $quality_result; } else { $quality = $this->get_quality(); } try { if ('image/jpeg' == $this->mime_type) { $this->image->setImageCompressionQuality($quality); $this->image->setImageCompression(imagick::COMPRESSION_JPEG); } else { $this->image->setImageCompressionQuality($quality); } } catch (Exception $e) { return new WP_Error('image_quality_error', $e->getMessage()); } return true; }
/** * @param string $file * @param int $quality * * @throws \ManaPHP\Image\Adapter\Exception */ public function save($file, $quality = 80) { $file = $this->alias->resolve($file); $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); $this->_image->setFormat($ext); if ($ext === 'gif') { $this->_image->optimizeImageLayers(); } else { if ($ext === 'jpg' || $ext === 'jpeg') { $this->_image->setImageCompression(\Imagick::COMPRESSION_JPEG); $this->_image->setImageCompressionQuality($quality); } } $dir = dirname($file); if (!@mkdir($dir, 0755, true) && !is_dir($dir)) { throw new ImagickException('create `:dir` image directory failed: :message', ['dir' => $dir, 'message' => error_get_last()['message']]); } if (!$this->_image->writeImage($file)) { throw new ImagickException('save `:file` image file failed', ['file' => $file]); } }
/** * Resizes image * @param string $src path to image * @param array $params resize parameters * @return array content and format */ public static function resize($src, $params) { $img_functions = self::supportedFormats(); $ext = $params['ext']; $new_width = $params['new_width']; $new_height = $params['new_height']; $dst_width = $params['dst_width']; $dst_height = $params['dst_height']; $width = $params['width']; $height = $params['height']; $bg_color = $params['bg_color']; $convert_to = $params['convert_to']; $jpeg_quality = $params['jpeg_quality']; $x = $params['x']; $y = $params['y']; self::$image->readImage($src); self::$image->scaleImage($new_width, $new_height, true); if ($convert_to == 'original') { $convert_to = $ext; } elseif (!empty($img_functions[$convert_to])) { $convert_to = $convert_to; } else { $convert_to = key($img_functions); } $canvas = new \Imagick(); $canvas->newImage($dst_width, $dst_height, $bg_color); // Convert images with CMYK colorspace to sRGB if (self::$image->getImageColorspace() == \Imagick::COLORSPACE_CMYK && method_exists(self::$image, 'transformimagecolorspace')) { self::$image->transformimagecolorspace(\Imagick::COLORSPACE_SRGB); } $canvas->compositeImage(self::$image, \Imagick::COMPOSITE_OVER, $x, $y); if ($convert_to == 'jpg') { $canvas->setImageCompressionQuality($jpeg_quality); } $canvas->setImageFormat($convert_to); $content = $canvas->getImageBlob(); $canvas->clear(); self::$image->clear(); return array($content, $convert_to); }
/** * Prepare the image for output, scaling and flattening as required * * @since 2.10 * @uses self::$image updates the image in this Imagick object * * @param integer zero or new width * @param integer zero or new height * @param boolean proportional fit (true) or exact fit (false) * @param string output MIME type * @param integer compression quality; 1 - 100 * * @return void */ private static function _prepare_image($width, $height, $best_fit, $type, $quality) { if (is_callable(array(self::$image, 'scaleImage'))) { if (0 < $width && 0 < $height) { // Both are set; use them as-is self::$image->scaleImage($width, $height, $best_fit); } elseif (0 < $width || 0 < $height) { // One is set; scale the other one proportionally if reducing $image_size = self::$image->getImageGeometry(); if ($width && isset($image_size['width']) && $width < $image_size['width']) { self::$image->scaleImage($width, 0); } elseif ($height && isset($image_size['height']) && $height < $image_size['height']) { self::$image->scaleImage(0, $height); } } else { // Neither is specified, apply defaults self::$image->scaleImage(150, 0); } } if (0 < $quality && 101 > $quality) { if ('image/jpeg' == $type) { self::$image->setImageCompressionQuality($quality); self::$image->setImageCompression(imagick::COMPRESSION_JPEG); } else { self::$image->setImageCompressionQuality($quality); } } if ('image/jpeg' == $type) { if (is_callable(array(self::$image, 'setImageBackgroundColor'))) { self::$image->setImageBackgroundColor('white'); } if (is_callable(array(self::$image, 'mergeImageLayers'))) { self::$image = self::$image->mergeImageLayers(imagick::LAYERMETHOD_FLATTEN); } elseif (is_callable(array(self::$image, 'flattenImages'))) { self::$image = self::$image->flattenImages(); } } }
/** * Output an image to buffer or return as string * * @param string $type Image format * @param boolean $buffer Output or return? * @return mixed * @throws Engine_Image_Adapter_Exception If unable to output */ public function output($type = 'jpeg', $buffer = false) { $this->_checkOpenImage(); // Set file type if ($type == 'jpg') { $type = 'jpeg'; } $type = strtoupper($type); if ($type !== $this->_resource->getImageFormat()) { $this->_resource->setImageFormat($type); } // Set quality if (null !== $this->_quality) { $this->_resource->setImageCompressionQuality($this->_quality); } // Output if ($buffer) { return (string) $this->_resource; } else { echo $this->_resource; } return $this; }
private function make_thumbnail_Imagick($src_path, $width, $height, $dest) { $image = new Imagick($src_path); # Select the first frame to handle animated images properly if (is_callable(array($image, 'setIteratorIndex'))) { $image->setIteratorIndex(0); } // устанавливаем качество $format = $image->getImageFormat(); if ($format == 'JPEG' || $format == 'JPG') { $image->setImageCompression(Imagick::COMPRESSION_JPEG); } $image->setImageCompressionQuality(85); $h = $image->getImageHeight(); $w = $image->getImageWidth(); // если не указана одна из сторон задаем ей пропорциональное значение if (!$width) { $width = round($w * ($height / $h)); } if (!$height) { $height = round($h * ($width / $w)); } list($dx, $dy, $wsrc, $hsrc) = $this->crop_coordinates($height, $h, $width, $w); // обрезаем оригинал $image->cropImage($wsrc, $hsrc, $dx, $dy); $image->setImagePage($wsrc, $hsrc, 0, 0); // Strip out unneeded meta data $image->stripImage(); // уменьшаем под размер $image->scaleImage($width, $height); $image->writeImage($dest); chmod($dest, 0755); $image->clear(); $image->destroy(); return true; }
private function createThumb($url, $filename, $type, $width, $height) { # Check dependencies self::dependencies(isset($this->database, $this->settings, $url, $filename, $type, $width, $height)); # Call plugins $this->plugins(__METHOD__, 0, func_get_args()); # Size of the thumbnail $newWidth = 200; $newHeight = 200; $photoName = explode('.', $filename); $newUrl = LYCHEE_UPLOADS_THUMB . $photoName[0] . '.jpeg'; $newUrl2x = LYCHEE_UPLOADS_THUMB . $photoName[0] . '@2x.jpeg'; # Create thumbnails with Imagick if (extension_loaded('imagick') && $this->settings['imagick'] === '1') { # Read image $thumb = new Imagick(); $thumb->readImage($url); $thumb->setImageCompressionQuality($this->settings['thumbQuality']); $thumb->setImageFormat('jpeg'); # Copy image for 2nd thumb version $thumb2x = clone $thumb; # Create 1st version $thumb->cropThumbnailImage($newWidth, $newHeight); $thumb->writeImage($newUrl); $thumb->clear(); $thumb->destroy(); # Create 2nd version $thumb2x->cropThumbnailImage($newWidth * 2, $newHeight * 2); $thumb2x->writeImage($newUrl2x); $thumb2x->clear(); $thumb2x->destroy(); } else { # Create image $thumb = imagecreatetruecolor($newWidth, $newHeight); $thumb2x = imagecreatetruecolor($newWidth * 2, $newHeight * 2); # Set position if ($width < $height) { $newSize = $width; $startWidth = 0; $startHeight = $height / 2 - $width / 2; } else { $newSize = $height; $startWidth = $width / 2 - $height / 2; $startHeight = 0; } # Create new image switch ($type) { case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break; case 'image/png': $sourceImg = imagecreatefrompng($url); break; case 'image/gif': $sourceImg = imagecreatefromgif($url); break; default: Log::error($this->database, __METHOD__, __LINE__, 'Type of photo is not supported'); return false; break; } # Create thumb fastimagecopyresampled($thumb, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth, $newHeight, $newSize, $newSize); imagejpeg($thumb, $newUrl, $this->settings['thumbQuality']); imagedestroy($thumb); # Create retina thumb fastimagecopyresampled($thumb2x, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth * 2, $newHeight * 2, $newSize, $newSize); imagejpeg($thumb2x, $newUrl2x, $this->settings['thumbQuality']); imagedestroy($thumb2x); # Free memory imagedestroy($sourceImg); } # Call plugins $this->plugins(__METHOD__, 1, func_get_args()); return true; }
/** * @static 使用ImageMagick压缩图片 * @param string $srcPath 图片地址 * @return bool */ public static function compress($srcPath = '', $quality = 80) { if (!extension_loaded('imagick') || empty($srcPath)) { return false; } try { $imagick = new Imagick(); if (empty($imagick)) { echo 1; } if (!$imagick->readImage($srcPath)) { echo 2; } if (!$imagick->setImageCompression(Imagick::COMPRESSION_JPEG)) { echo 4; } if (!$imagick->setImageCompressionQuality($quality)) { echo 5; } if (!$imagick->stripImage()) { echo 3; } if (!$imagick->writeImage()) { echo 6; } if (!$imagick->clear()) { echo 7; } if (!$imagick->destroy()) { echo 8; } return true; } catch (Exception $e) { echo $e->getMessage(); return false; } }
/** * fitImage * @param string $sourceImg The path to the image to fit * @param string $destImg The path where the resized image will be saved * @param int $maxW Max width * @param int $maxH Max height * */ public static function fitImage($sourceImg, $destImg, $maxW, $maxH) { $image = new Imagick($sourceImg); $image->resizeImage($maxW, $maxH, Imagick::FILTER_CATROM, 1, TRUE); // Set to use jpeg compression $image->setImageCompression(Imagick::COMPRESSION_JPEG); // Set compression level (1 lowest quality, 100 highest quality) $image->setImageCompressionQuality(80); // Strip out unneeded meta data $image->stripImage(); // Writes resultant image to output directory $image->writeImage($destImg); // Destroys Imagick object $image->destroy(); }