function IMAGEN_tipo_normal() { $escalado = 'IMG/i/m/' . $_GET['ancho'] . '_' . $_GET['alto'] . '_' . $_GET['sha1']; $origen = 'IMG/i/' . $_GET['sha1']; $ancho = $_GET['ancho']; $alto = $_GET['alto']; if (@($ancho * $alto) > 562500) { die('La imagen solicitada excede el límite de este servicio'); } if (!file_exists($escalado)) { $im = new Imagick($origen); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(85); $im->setImageFormat('jpeg'); $im->stripImage(); $im->despeckleImage(); $im->sharpenImage(0.5, 1); //$im->reduceNoiseImage(0); $im->setInterlaceScheme(Imagick::INTERLACE_PLANE); $im->resizeImage($ancho, $alto, imagick::FILTER_LANCZOS, 1); $im->writeImage($escalado); $im->destroy(); } $im = new Imagick($escalado); $output = $im->getimageblob(); $outputtype = $im->getFormat(); $im->destroy(); header("Content-type: {$outputtype}"); header("Content-length: " . filesize($escalado)); echo $output; }
public function run($file, $temp_dir) { $info = $this->getImageDetails($file); $image = new Imagick(); $image->readImage($file); if ($info['ext'] == 'jpg') { $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setCompressionQuality($this->settings['quality']); $image->setImageFormat('jpeg'); } if ($info['ext'] == 'gif') { //remove the canvas (for .gif) $image->setImagePage(0, 0, 0, 0); } //crop and resize the image $image->resizeImage($this->settings['width'], $this->settings['height'], Imagick::FILTER_LANCZOS, 1, true); $image->writeImage($file); return TRUE; }
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(); }
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); } }
/** * Associates the model with the file * @param string $filePath * @return boolean */ public function setFile($filePath) { if (!file_exists($filePath)) { return false; } $info = getimagesize($filePath); $imageWidth = $info[0]; $imageHeight = $info[1]; $image = new Imagick(); $image->readimage($filePath); $image->setResourceLimit(Imagick::RESOURCETYPE_MEMORY, 1); $maxSize = 1920; if ($imageWidth > $maxSize && $imageWidth > $imageHeight) { $image->thumbnailimage($maxSize, null); } elseif ($imageHeight > $maxSize && $imageHeight > $imageWidth) { $image->thumbnailimage(null, $maxSize); } $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setCompressionQuality(80); $image->stripimage(); $this->size = filesize($filePath); $this->type = $info['mime']; $this->width = $info[0]; $this->height = $info[1]; $this->content = $image->getImageBlob(); $this->expireAt(time() + static::EXP_DAY); return true; }
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 storeBase64Image($name, $dir, $fileContentBase64) { $uploadDir = $this->rootDir . '/../web' . $dir; if (!is_dir($uploadDir)) { mkdir($uploadDir, 0777, true); } $image = new \Imagick(); $data = explode(',', $fileContentBase64); $fileContent = base64_decode($data[1]); $image->readImageBlob($fileContent); $filename = $name . "." . time() . '.jpg'; $image->setImageFormat('jpeg'); $image->setCompression(\Imagick::COMPRESSION_JPEG); $image->setCompressionQuality(50); $image->writeImage($uploadDir . $filename); return $filename; }
/** * Converts the background image to the correct type and quality * @param $filename */ protected function convertImage($filename, $bookHeight, $bookWidth) { if ($this->backgroundImageType == 'png') { return $filename; } $newFilename = substr($filename, 0, -4) . '.jpg'; $img = new Imagick($filename); $img->setformat('jpeg'); $img->setCompression(imagick::COMPRESSION_JPEG); if ($this->backgroundResize) { $img->resizeImage($bookWidth, $bookHeight, Imagick::FILTER_LANCZOS, 1); } $img->writeimage($newFilename); return $newFilename; }
public function doUpload($key, $sw = 0, $sh = 0) { $config = Zend_Registry::get('config'); if (array_key_exists($key, $_FILES) && $_FILES[$key]['size']) { try { $image = new Imagick(); $image->readImageBlob(file_get_contents($_FILES[$key]['tmp_name'])); $iw = $image->getImageWidth(); $ih = $image->getImageHeight(); $uniqid = uniqid('', true); $path_n = APPLICATION_PATH . "/images/thumbnail/" . $uniqid . ".jpg"; $url_n = $config->app->base_url . "/images/thumbnail/" . $uniqid . ".jpg"; if ($sw == 0 && $sh == 0) { $sw = $iw; $sh = $ih; $path_n = APPLICATION_PATH . "/images/" . $uniqid . ".jpg"; $url_n = $config->app->base_url . "/images/" . $uniqid . ".jpg"; } if ($sw == $iw && $sh == $ih) { $fh = fopen($path_n, 'wb'); fwrite($fh, $image->getImagesBlob()); fclose($fh); } elseif ($sw / $iw > $sh / $ih) { $ww = intval($iw * $sh / $ih); $hh = intval($ih * $sw / $iw); $image->scaleImage($sw, $hh); $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, 0, intval(($sh - $hh) / 2)); $im2->setImageFormat('jpeg'); $fh = fopen($path_n, 'wb'); fwrite($fh, $im2->getImagesBlob()); fclose($fh); } else { $ww = intval($iw * $sh / $ih); $hh = intval($ih * $sw / $iw); if ($sw == 0 && $sh == 0) { $ww = 1; $hh = 1; $image->scaleImage($ww, $sh); $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, intval(($sw - $ww) / 2), 0); $im2->setImageFormat('jpeg'); } else { //for thumbnail set compression to 90 $image->scaleImage($ww, $sh); $im2 = new Imagick(); $im2->setCompression(Imagick::COMPRESSION_JPEG); $im2->setCompressionQuality(90); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, intval(($sw - $ww) / 2), 0); $im2->setImageFormat('jpeg'); } /* $image->scaleImage($ww, $sh); $im2 = new Imagick(); $im2->newImage($sw, $sh, "none"); $im2->compositeImage($image, Imagick::COMPOSITE_DEFAULT, intval(($sw - $ww) / 2), 0); $im2->setImageFormat('jpeg'); */ $fh = fopen($path_n, 'wb'); fwrite($fh, $im2->getImagesBlob()); fclose($fh); } return $url_n; } catch (Exception $e) { return null; } } else { return null; } }
/** * Creates PDF document thumbnail * @param $docPath * @param $thumbDirectory * @param $docId * @param int $thumbsizeX * @param int $thumbsizeY * @return bool|string */ public static function cratePDFThumbnail($docPath, $thumbDirectory, $docId, $thumbsizeX = 400, $thumbsizeY = 600, $batch=false) { $imagesPath = Yii::getPathOfAlias('webroot') . '/protected/data/'; // Path to your images directory on the server $thumbsPath = $imagesPath . $thumbDirectory; // Path to image thumbnails directory $temp_file_path = $thumbsPath . '/' . ($batch ? 'batch_' : '') . $docId ; /* Pdf convertion Variant 1*/ $im = new Imagick(Yii::getPathOfAlias('webroot') . '/' . $docPath); $im->setImageColorspace(255); $im->setResolution($thumbsizeX, $thumbsizeY); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(60); $im->setImageFormat('jpeg'); $im->writeImage($temp_file_path); $im->clear(); $im->destroy(); /* * Pdf convertion Variant 2 Works with better quality. Needs exec rights and **/ /*$path_to_extracted_file = Yii::getPathOfAlias('webroot') . '/' . $docPath; exec('pdftoppm '.$path_to_extracted_file.' -jpeg -scale-to-x 600 -scale-to-y -1 '.$temp_file_path); $temp_file_path=$temp_file_path.'-1.jpg'; exec('chmod 755 '. $temp_file_path); */ // A little error-checking overkill if (!file_exists($temp_file_path)) { return false; } else { return $temp_file_path; } }
protected function _imageResizeAndSave($object) { $path = APPLICATION_ROOT . '/public_html/images/events/'; if (!is_dir($path)) { mkdir($path, 0777, true); } $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_News_Validator'); $msgr->addMessage('file', $adapter->getMessages(), 'title'); } if ($object->getImage() == null) { $object->setImage(''); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if (!$file['tmp_name']) { continue; } $path0 = $path . "280x160/"; if (!is_dir($path0)) { mkdir($path0, 0777, true); } $path1 = $path . "630x355/"; if (!is_dir($path1)) { mkdir($path1, 0777, true); } $filename = $object->createThumbName($file['name']) . '_' . time() . '.jpg'; $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(280, 160); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(80); $image->setImageFormat('jpeg'); $image->writeImage($path0 . $filename); $image->clear(); $image->destroy(); $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(630, 355); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(80); $image->setImageFormat('jpeg'); $image->writeImage($path1 . $filename); $image->clear(); $image->destroy(); unlink($file['tmp_name']); $object->setImage($filename); } }
function Imagen__CrearMiniatura($Origen, $Destino, $Ancho = 100, $Alto = 100) { $im = new Imagick($Origen); $im->setImageColorspace(255); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(80); $im->setImageFormat('jpeg'); list($newX, $newY) = scaleImage($im->getImageWidth(), $im->getImageHeight(), $Ancho, $Alto); $im->thumbnailImage($newX, $newY, false); return $im->writeImage($Destino); }
function reduire_image($userfile_name) { global $pmb_vignette_x; global $pmb_vignette_y; global $base_path; global $pmb_curl_available; if (!$pmb_vignette_x) { $pmb_vignette_x = 100; } if (!$pmb_vignette_y) { $pmb_vignette_y = 100; } $src_image = ''; if (file_exists("{$base_path}/temp/{$userfile_name}")) { $bidon = "{$base_path}/temp/{$userfile_name}"; $source_file = $bidon . "[0]"; } else { $bidon = $userfile_name; //Il s'agit d'une url, on copie le fichier en local $nom_temp = session_id() . microtime(); $nom_temp = str_replace(' ', '_', $nom_temp); $nom_temp = str_replace('.', '_', $nom_temp); $fichier_tmp = "{$base_path}/temp/" . $nom_temp; if ($pmb_curl_available) { $aCurl = new Curl(); $aCurl->save_file_name = $fichier_tmp; $aCurl->get($userfile_name); } else { $handle = fopen($userfile_name, "rb"); $filecontent = stream_get_contents($handle); fclose($handle); $fd = fopen($fichier_tmp, "w"); fwrite($fd, $filecontent); fclose($fd); } $source_file = $fichier_tmp . "[0]"; } $error = true; if (extension_loaded('imagick')) { mysql_set_wait_timeout(3600); $error = false; try { $img = new Imagick(); $img->readImage($source_file); if ($img->getImageWidth() > $pmb_vignette_x || $img->getImageHeight() > $pmb_vignette_y) { // Si l'image est trop grande on la réduit $img->thumbnailimage($pmb_vignette_x, $pmb_vignette_y, true); } $img->setImageFormat("png"); $img->setCompression(Imagick::COMPRESSION_LZW); $img->setCompressionQuality(90); $contenu_vignette = $img->getImageBlob(); } catch (Exception $ex) { $error = true; } unlink($fichier_tmp); } if ($error) { $size = @getimagesize($bidon); /* ".gif"=>"1", ".jpg"=>"2", ".jpeg"=>"2", ".png"=>"3", ".swf"=>"4", ".psd"=>"5", ".bmp"=>"6"); */ switch ($size[2]) { case 1: $src_img = imagecreatefromgif($bidon); break; case 2: $src_img = imagecreatefromjpeg($bidon); break; case 3: $src_img = imagecreatefrompng($bidon); break; case 6: $src_img = imagecreatefromwbmp($bidon); break; default: break; } $erreur_vignette = 0; if ($src_img) { $rs = $pmb_vignette_x / $pmb_vignette_y; $taillex = imagesx($src_img); $tailley = imagesy($src_img); if (!$taillex || !$tailley) { return ""; } if ($taillex > $pmb_vignette_x || $tailley > $pmb_vignette_y) { $r = $taillex / $tailley; if ($r < 1 && $rs < 1) { //Si x plus petit que y et taille finale portrait //Si le format final est plus large en proportion if ($rs > $r) { $new_h = $pmb_vignette_y; $new_w = $new_h * $r; } else { $new_w = $pmb_vignette_x; $new_h = $new_w / $r; } } else { if ($r < 1 && $rs >= 1) { //Si x plus petit que y et taille finale paysage $new_h = $pmb_vignette_y; $new_w = $new_h * $r; } else { if ($r > 1 && $rs < 1) { //Si x plus grand que y et taille finale portrait $new_w = $pmb_vignette_x; $new_h = $new_w / $r; } else { //Si x plus grand que y et taille finale paysage if ($rs < $r) { $new_w = $pmb_vignette_x; $new_h = $new_w / $r; } else { $new_h = $pmb_vignette_y; $new_w = $new_h * $r; } } } } } else { $new_h = $tailley; $new_w = $taillex; } $dst_img = imagecreatetruecolor($pmb_vignette_x, $pmb_vignette_y); ImageSaveAlpha($dst_img, true); ImageAlphaBlending($dst_img, false); imagefilledrectangle($dst_img, 0, 0, $pmb_vignette_x, $pmb_vignette_y, imagecolorallocatealpha($dst_img, 0, 0, 0, 127)); imagecopyresized($dst_img, $src_img, round(($pmb_vignette_x - $new_w) / 2), round(($pmb_vignette_y - $new_h) / 2), 0, 0, $new_w, $new_h, ImageSX($src_img), ImageSY($src_img)); imagepng($dst_img, "{$base_path}/temp/" . SESSid); $fp = fopen("{$base_path}/temp/" . SESSid, "r"); $contenu_vignette = fread($fp, filesize("{$base_path}/temp/" . SESSid)); if (!$fp || $contenu_vignette == "") { $erreur_vignette++; } fclose($fp); unlink("{$base_path}/temp/" . SESSid); } else { $contenu_vignette = ''; } } return $contenu_vignette; }
/** * [postRequestAtLocal 上传图片 扩展(待完善)] * @param array $img_info [图片上传信息] * @param [type] $rel_path [生成的路径 ] * @return [type] [description] */ public function postRequestAtLocal($img_info = array(), $rel_path = null) { if (empty($img_info) || !$rel_path) { return false; } $full_path = self::LOCAL_PATH . '/' . $rel_path; $rdir = dirname($full_path); if (!file_exists($rdir)) { $oldumask = umask(0); mkdir($rdir, 0777, TRUE); chmod($rdir, 0777); umask($oldumask); } // Step 3:图片处理 $compress = empty($_GET['compress']) || $_GET['cmopress'] != 'n' ? 'y' : $_GET['compress']; $im = new Imagick(); try { $im->readImageBlob(file_get_contents($img_info['tmp_name'])); } catch (Exception $e) { die($e->getMessage()); } // 获取图片格式 $image_format = strtoupper($im->getImageFormat()); switch ($image_format) { case 'PNG': $new_name = $full_path . self::DEFAULT_SUFFIX; $full_path .= ".png"; $im->setImageColorspace(Imagick::COLORSPACE_RGB); $im->setImageFormat("PNG") or die("Error:"); if ($compress != "n") { $im->setCompressionQuality(80) or die("Error:"); } $im->writeImage($full_path) or die("Error:"); rename($full_path, $new_name); $full_path = $new_name; $type = "image/png"; break; case 'GIF': $new_name = $full_path . self::DEFAULT_SUFFIX; $full_path .= ".gif"; $im->setImageColorspace(Imagick::COLORSPACE_RGB); $im->setImageFormat("GIF") or die("Error:"); if ($compress != "n") { $im->setCompressionQuality(80) or die("Error:"); } $im->writeImage($full_path, TRUE) or die("Error:"); rename($full_path, $new_name); $full_path = $new_name; $type = "image/gif"; break; default: $full_path .= self::DEFAULT_SUFFIX; $im->setImageColorspace(imagick::COLORSPACE_RGB); $im->setImageFormat("JPG") or die("Error:"); if ($compress != "n") { $im->setCompression(Imagick::COMPRESSION_JPEG) or die("Error:"); $im->setCompressionQuality(80) or die("Error:"); } $im->writeImage($full_path) or die("Error:"); $type = "image/jpeg"; break; } }
public function addAction() { SxCms_Acl::requireAcl('page', 'page.add'); $system = new Zend_Session_Namespace('System'); $wizard = new Zend_Session_Namespace('Cms_PageWizard'); if ($this->_getParam('reset')) { $wizard->page = new SxCms_Page(); $wizard->page->setLanguage($system->lng); $this->_helper->redirector->gotoSimple('wizard-type', 'page'); } $mapper = new SxCms_Group_DataMapper(); $this->view->groups = $mapper->getAll(); $revision = new SxCms_Page_Revision(); $revision->setApproved(true); $revision->setNotes($this->admin_tmx->_('newpagecreated')); if ($wizard->page->getId() !== false) { $revision->setApproved(false); $revision->setNotes($this->admin_tmx->_('pageedited')); } if ($this->getRequest()->isPost()) { $path = APPLICATION_ROOT . '/public_html/images/thumbs/1200x160/'; $path1 = APPLICATION_ROOT . '/public_html/images/thumbs/400x180/'; if (!is_dir($path)) { mkdir($path, 0777, true); } if (!is_dir($path1)) { mkdir($path1, 0777, true); } $system->lng = $this->_getParam('lang'); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxCms_Page'); $msgr->addMessage('file', $adapter->getMessages(), 'title'); } $wizard->page->setThumb(null); $files = $adapter->getFileInfo(); foreach ($files as $file) { if (!$file['tmp_name']) { continue; } $filename = uniqid() . '.jpg'; $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(1200, 190); $image->setCompressionQuality(100); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageFormat('jpeg'); $image->writeImage($path . $filename); $image->clear(); $image->destroy(); $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(400, 180); $image->setCompressionQuality(100); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageFormat('jpeg'); $image->writeImage($path1 . $filename); $image->clear(); $image->destroy(); unlink($file['tmp_name']); $wizard->page->setThumb($filename); } $wizard->page->clearPermissions(); foreach ((array) $this->_getParam('group') as $groupId) { $group = new SxCms_Group(); $group->setId($groupId); $wizard->page->addPermission($group); } $wizard->page->setTitle($this->_getParam('title'))->setTitleFallback($this->_getParam('title_fb'))->setSummary($this->_getParam('summary'))->setSummaryFallback($this->_getParam('summary_fb'))->setContent($this->_getParam('contenti'))->setContentFallback($this->_getParam('content_fb'))->setSource($this->_getParam('source'))->setSourceFallback($this->_getParam('source_fb'))->setLayout($this->_getParam('layout', 'default'))->addTag(explode("\n", $this->_getParam('tags')))->setLink($this->_getParam('link'))->setNavigation($this->_getParam('menu'), false)->setSitemap($this->_getParam('sitemap'), false)->setAllowComments($this->_getParam('comments'), false)->setInvisible($this->_getParam('invisible'))->setSeoTitle($this->_getParam('seotitle'))->setSeoTags($this->_getParam('seotags'))->setSeoDescription($this->_getParam('seodescription')); $revision->setNotes($this->_getParam('notes')); $datePublished = $this->_getParam('date_published') . ' ' . $this->_getParam('publish_h') . ':' . $this->_getParam('publish_i') . ':00'; $dateExpired = null; if ($this->_getParam('date_expired')) { $dateExpired = $this->_getParam('date_expired') . ' ' . $this->_getParam('expire_h') . ':' . $this->_getParam('expire_i') . ':00'; } $wizard->page->setDatePublished($datePublished)->setDateExpired($dateExpired); if ($this->_getParam('translation')) { $wizard->page->markTranslationInvalid(); } if ($wizard->page->isValid()) { $config = Zend_Registry::get('config'); if ($wizard->page->getId() === false) { $lngs = $config->system->language; } else { $lngs[$wizard->page->getLanguage()] = null; } $wizard->page->save(); foreach ($lngs as $lng => $slng) { $revision->setNotes($this->_getParam('notes'))->setLanguage($lng)->setTitle($wizard->page->getTitle())->setTitleFallback($wizard->page->hasTitleFallback())->setSummary($wizard->page->getSummary())->setSummaryFallback($wizard->page->hasSummaryFallback())->setContent($wizard->page->getContent())->setContentFallback($wizard->page->hasContentFallback())->setSource($wizard->page->getSource())->setSourceFallback($wizard->page->hasSourceFallback())->setLink($wizard->page->getLink())->setLinkFallback($wizard->page->hasLinkFallback())->setPageId($wizard->page->getId())->setInvisible($wizard->page->getInvisible()); $revision->setSeoTitle($wizard->page->getSeoTitle())->setSeoTags($wizard->page->getSeoTags())->setSeoDescription($wizard->page->getSeoDescription()); $revision->save(); if (!$this->_getParam('revision')) { $revision->approve(); } } $flashMessenger = $this->_helper->getHelper('FlashMessenger'); $flashMessenger->addMessage($this->admin_tmx->_('pagesavesuccess')); if ($wizard->page->getType() == SxCms_Page::ARTICLE) { $this->_helper->redirector->gotoSimple('news', 'page'); } else { $this->_helper->redirector->gotoSimple('index', 'page'); } $wizard->unsetAll(); } $wizard->page->setDatePublished($this->_getParam('date_published'))->setDateExpired($this->_getParam('date_expired')); } $this->view->page = $wizard->page; $this->view->messages = Sanmax_MessageStack::getInstance('SxCms_Page'); $this->view->revision = $revision; }
public function resizeAndSave() { $path = APPLICATION_ROOT . '/public_html/images/subcategory/'; $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_Faq'); $msgr->addMessage('file', $adapter->getMessages(), 'file'); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if ($file['tmp_name'] == '') { continue; } $path0 = $path . "228X123/"; $path1 = $path . "466X123/"; $filename = $this->_faq->createThumbName($file['name']) . '_' . time() . '.jpg'; $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(228, 123); $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(466, 123); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(100); $image->setImageFormat('jpeg'); $image->writeImage($path1 . $filename); $image->clear(); $image->destroy(); unlink($file['tmp_name']); $this->_faq->setPicture($filename); } }
function text2image($text, $width, $margin, $size, $font, $align, $stroke, $bg, $color, $scolor, $out) { $text = html_entity_decode($text); $lines = array(); //break up the text on the line $imageForMetric = new Imagick(); $drawForMetric = new ImagickDraw(); $drawForMetric->setFont($font); $drawForMetric->setFontSize($size); $explicitLines = preg_split('/\\n|\\r\\n?/', $text); $key = 0; foreach ($explicitLines as $line) { $words = explode(" ", $line); $line = $words[0]; for ($i = 1; $i < count($words); $i++) { if ($imageForMetric->queryFontMetrics($drawForMetric, $line . " " . $words[$i])['textWidth'] >= $width - $margin * 2) { $key++; $lines[$key]['text'] = $line; $line = $words[$i]; } else { $line .= " " . $words[$i]; } } $key++; $lines[$key]['text'] = $line; $lines[$key]['type'] = 'last'; } $imageForMetric->destroy(); $drawForMetric->destroy(); //line height $lineHeightPx = $size * 1.5; //margin top and bottom (can leave $pad=$margin;) if ($size < 16) { $pad = $size / 2; } elseif ($size < 26) { $pad = $size / 3; } elseif ($size < 36) { $pad = $size / 4; } else { $pad = 0; } //height image $textHeight = count($lines) * $lineHeightPx + $pad * 2; $image = new Imagick(); $draw = new ImagickDraw(); $pixel = new ImagickPixel('#' . $bg); $image->newImage($width, $textHeight + $lineHeightPx / 2, $pixel); $draw->setFillColor('#' . $color); $draw->setFont($font); $draw->setFontSize($size); //for setTextAlignment if ($align == 'center') { $alignNumber = 2; } elseif ($align == 'right') { $alignNumber = 3; } else { $alignNumber = 1; } $draw->setTextAlignment($alignNumber); $draw->setTextEncoding('UTF-8'); //x start position if ($align == 'center') { $xpos = $width / 2; } elseif ($align == 'right') { $xpos = $width - $margin; } else { $xpos = $margin; } //text stroke if ($stroke) { $drawstroke = new ImagickDraw(); $drawstroke->setFillColor('#' . $scolor); $drawstroke->setFont($font); $drawstroke->setFontSize($size); $drawstroke->setTextAlignment($alignNumber); $drawstroke->setTextEncoding('UTF-8'); } //y start position $ypos = $lineHeightPx + $pad; $i = 0; foreach ($lines as $value => $line) { if ($align == 'justify' && (!isset($lines[$value]['type']) || $lines[$value]['type'] != 'last')) { //justify for all lines (except last) $line = trim($lines[$value]['text']); $sp = 0; $j = 0; $line = preg_replace("/ +/", " ", $line); $spaces = substr_count($line, ' '); $word = explode(' ', $line); //word metrics $metrics = 0; foreach ($word as $w) { $metrics = $metrics + $image->queryFontMetrics($draw, $w)['textWidth']; } $spacewidth = ($width - $margin * 2 - $metrics) / $spaces; foreach ($word as $w) { if ($w !== '') { $j++; if ($j > 1) { $sp = $sp + $spacewidth; } if ($stroke) { //draw stroke $ys = 0; $xs = $stroke; $d = (5 - $stroke * 4) / 4; while ($xs >= $ys) { $image->annotateImage($drawstroke, $xpos + $sp + $stroke, $ypos + $i * $lineHeightPx + $ys, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp + $stroke, $ypos + $i * $lineHeightPx - $ys, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp - $stroke, $ypos + $i * $lineHeightPx + $ys, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp - $stroke, $ypos + $i * $lineHeightPx - $ys, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp + $ys, $ypos + $i * $lineHeightPx + $stroke, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp + $ys, $ypos + $i * $lineHeightPx - $stroke, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp - $ys, $ypos + $i * $lineHeightPx + $stroke, 0, $w); $image->annotateImage($drawstroke, $xpos + $sp - $ys, $ypos + $i * $lineHeightPx - $stroke, 0, $w); if ($d < 0) { $d += 2 * $ys + 1; } else { $d += 2 * ($ys - $xs) + 1; $xs--; } $ys++; } } //draw word $image->annotateImage($draw, $xpos + $sp, $ypos + $i * $lineHeightPx, 0, $w); //space width $sp = $sp + $image->queryFontMetrics($draw, $w)['textWidth']; } } } else { if ($stroke) { //draw stroke $ys = 0; $xs = $stroke; $d = (5 - $stroke * 4) / 4; while ($xs >= $ys) { $image->annotateImage($drawstroke, $xpos + $stroke, $ypos + $i * $lineHeightPx + $ys, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos + $stroke, $ypos + $i * $lineHeightPx - $ys, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos - $stroke, $ypos + $i * $lineHeightPx + $ys, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos - $stroke, $ypos + $i * $lineHeightPx - $ys, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos + $ys, $ypos + $i * $lineHeightPx + $stroke, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos + $ys, $ypos + $i * $lineHeightPx - $stroke, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos - $ys, $ypos + $i * $lineHeightPx + $stroke, 0, $lines[$value]['text']); $image->annotateImage($drawstroke, $xpos - $ys, $ypos + $i * $lineHeightPx - $stroke, 0, $lines[$value]['text']); if ($d < 0) { $d += 2 * $ys + 1; } else { $d += 2 * ($ys - $xs) + 1; $xs--; } $ys++; } } //draw line $image->annotateImage($draw, $xpos, $ypos + $i * $lineHeightPx, 0, $lines[$value]['text']); } $i++; } //save image to png $image->setCompressionQuality(100); $image->setCompression(Imagick::COMPRESSION_NO); $image->setImageFormat('png'); $image->writeImage('png24:' . $out); $image->destroy(); }
public function run($pdf, $opts) { // catch objects if (!isset($opts)) { $opts = ''; } // get options $opts = json_decode($opts); // set up an object if (!$opts) { $opts = (object) array(); } // default options if (!property_exists($opts, 'nocache')) { $opts->nocache = false; } if (!property_exists($opts, 'pagemaxwidth')) { $opts->pagemaxwidth = 1000; } if (!property_exists($opts, 'pagemaxheight')) { $opts->pagemaxheight = 1000; } if (!property_exists($opts, 'thumbmaxwidth')) { $opts->thumbmaxwidth = 100; } if (!property_exists($opts, 'thumbmaxheight')) { $opts->thumbmaxheight = 75; } // create a cache id $cachemod = md5($pdf); // does it exist in the cache, if so return it if (!$opts->nocache && file_exists($this->cachedir . '/' . $cachemod . '/json.txt')) { return json_decode(file_get_contents($this->cachedir . '/' . $cachemod . '/json.txt')); } try { // create our cache directory mkdir($this->cachedir . '/' . $cachemod, 0777, true); // filename $filename = $this->cachedir . '/' . $cachemod . '/' . basename($pdf); // download the file $bytes = file_put_contents($filename, file_get_contents($pdf)); // make sure we downloaded something if ($bytes === FALSE) { $json = array('error' => false, 'errormsg' => 'Could not download the PDF specified'); return $json; } // json to return $json = array('error' => false, 'pagecount' => 0, 'pdfurl' => $this->URL . $filename, 'thumbs' => array(), 'pages' => array(), 'geometry' => array('x' => 0, 'y' => 0)); // set up imagick instance $im = new Imagick(); // force resolution to screen $im->setResolution(72, 72); // read image $im->readImage($filename); // get image information $imageInfo = $im->identifyImage(); // ensure its a pdf! if (!$imageInfo || strpos(strtolower($imageInfo['format']), 'pdf') === FALSE) { $json = array('error' => false, 'errormsg' => 'The file specified is not a PDF!'); return $json; } // get geometry $geometry = $imageInfo['geometry']; $json['geometry'] = array('x' => $geometry['width'], 'y' => $geometry['height']); // resize ratio $ratio = 1; $thumbratio = 1; // landscape or portrait? if ($geometry['width'] > $geometry['height']) { if ($geometry['width'] > $opts->pagemaxwidth) { $ratio = $opts->pagemaxwidth / $geometry['width']; } } else { if ($geometry['height'] > $opts->pagemaxheight) { $ratio = $opts->pagemaxheight / $geometry['height']; } } // thumb ratio if ($geometry['width'] > $geometry['height']) { if ($geometry['width'] > $opts->thumbmaxwidth) { $thumbratio = $opts->thumbmaxwidth / $geometry['width']; } } else { if ($geometry['height'] > $opts->thumbmaxheight) { $thumbratio = $opts->thumbmaxheight / $geometry['height']; } } // get the number of pages $json['pagecount'] = $im->getNumberImages(); // loop over pagecount for ($i = 0; $i < $json['pagecount']; $i++) { // convert to jpg $im2 = new Imagick($filename . '[' . $i . ']'); // png for big image //$im2->setCompression(Imagick::COMPRESSION_PNG); $im2->setImageFormat('png'); $im2->setCompressionQuality(95.5); // main image max size $im2->resizeImage($geometry['width'] * $ratio, $geometry['height'] * $ratio, imagick::FILTER_UNDEFINED, 1); //write image on server $im2->writeImage($this->cachedir . '/' . $cachemod . '/page-' . $i . '.png'); // jpg for thumb $im2->setCompression(Imagick::COMPRESSION_JPEG); $im2->setCompressionQuality(95); $im2->setImageFormat('jpg'); // thumb resize $im2->resizeImage($geometry['width'] * $thumbratio, $geometry['height'] * $thumbratio, imagick::FILTER_UNDEFINED, 1); //write image on server $im2->writeImage($this->cachedir . '/' . $cachemod . '/thumb-' . $i . '.jpg'); // tidy up $im2->clear(); $im2->destroy(); // add to json $json['thumbs'][] = $this->CACHEURL . $cachemod . '/thumb-' . $i . '.jpg'; $json['pages'][] = $this->CACHEURL . $cachemod . '/page-' . $i . '.png'; } // tidy up $im->clear(); $im->destroy(); // put json into file file_put_contents($this->cachedir . '/' . $cachemod . '/json.txt', json_encode($json)); // return values return $json; } catch (exception $e) { return array('error' => true, 'errormsg' => $e->getMessage()); } }
$general = $XML->addChild('seccion'); $general->addAttribute("titulo", "Catalogo"); $general->addAttribute("pagina", ""); $pagina_actual = 1; while ($f = mysql_fetch_assoc($r)) { $ref = $general->addChild('ref'); //$ref->addAttribute("titulo",iconv('ISO-8859-1','UTF-8//TRANSLIT',$f['titulo'])); $ref->addAttribute("titulo", $f['titulo']); $ref->addAttribute("pagina", $pagina_actual); $cp = 'SELECT foto, pc.titulo FROM flores_productos_categoria LEFT JOIN flores_producto_contenedor AS pc USING(codigo_producto) LEFT JOIN flores_producto_variedad USING(codigo_producto) WHERE codigo_categoria=' . $f['codigo_categoria'] . ' GROUP BY codigo_producto'; $rp = db_consultar($cp); $pagina_actual += 1 + mysql_numrows($rp); while ($fp = mysql_fetch_assoc($rp)) { if (!file_exists('catalogo360/pages/' . $fp['foto'])) { $im = new Imagick('IMG/i/' . $fp['foto']); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(90); $im->setImageFormat('jpeg'); $im->stripImage(); $draw = new ImagickDraw(); $pixel = new ImagickPixel('gray'); $pixel->setColor('black'); $draw->setFont('flower.ttf'); $draw->setFontSize(30); $im->thumbnailImage(350, 525, false); $im->annotateImage($draw, 10, 45, 0, $fp['titulo']); $im->writeImage('catalogo360/pages/' . $fp['foto']); $im->clear(); $im->destroy(); unset($im); }
<?php if (array_key_exists("img", $_REQUEST)) { $image = $_REQUEST['img']; try { $img = new Imagick($image); if ($img->valid()) { if ($img->getImageWidth() > $img->getImageHeight()) { $img->rotateImage(new ImagickPixel('none'), 90); } $img->thumbnailImage(0, 160); if ($img->getImageWidth() > 128) { $img->thumbnailImage(128, 0); } $img->setImageFormat('bmp'); $img->setCompression(imagick::COMPRESSION_NO); $img->setImageDepth(24); $img->setImageMatte(false); $img->flopImage(); //$img->setImageAlphaChannel(imagick::ALPHACHANNEL_DEACTIVATE); $imgData = (string) $img; header("Content-Type: image/bmp"); header("Content-Length: " . strlen($imgData)); echo $img; } else { throw new Exception("image not valid"); } } catch (Exception $e) { //http_response_code(403); echo $e; }
public function resizeAndSave() { $path = APPLICATION_ROOT . '/public_html/images/doctors/'; if (!is_dir($path)) { mkdir($path, 0777, true); } $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_Doctor'); $msgr->addMessage('file', $adapter->getMessages(), 'file'); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if ($file['tmp_name'] == '') { continue; } $filename = $this->_doc->createThumbName($file['name']) . '_' . time() . '.png'; $path0 = $path . "100x100/"; $path1 = $path . "230x230/color/"; $path2 = $path . "230x230/fade/"; $path3 = $path . "110x110/color/"; $path4 = $path . "110x110/fade/"; if (!is_dir($path0)) { mkdir($path0, 0777, true); } if (!is_dir($path1)) { mkdir($path1, 0777, true); } if (!is_dir($path2)) { mkdir($path2, 0777, true); } if (!is_dir($path3)) { mkdir($path3, 0777, true); } if (!is_dir($path4)) { mkdir($path4, 0777, true); } $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(100, 100); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(100); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat('png32'); $image->writeImage($path0 . $filename); $image->clear(); $image->destroy(); $image1 = new Imagick($file['tmp_name']); $image1->cropThumbnailImage(230, 230); $image1->setCompression(Imagick::COMPRESSION_JPEG); $image1->setImageCompressionQuality(100); $image1->setBackgroundColor(new ImagickPixel('transparent')); $image1->setImageFormat('png32'); $image1->writeImage($path1 . $filename); $image1->setimagetype(Imagick::IMGTYPE_GRAYSCALE); $image1->writeImage($path2 . $filename); $image1->clear(); $image1->destroy(); $image1 = new Imagick($file['tmp_name']); $image1->cropThumbnailImage(110, 110); $image1->setCompression(Imagick::COMPRESSION_JPEG); $image1->setImageCompressionQuality(100); $image1->setBackgroundColor(new ImagickPixel('transparent')); $image1->setImageFormat('png32'); $image1->writeImage($path3 . $filename); $image1->setimagetype(Imagick::IMGTYPE_GRAYSCALE); $image1->writeImage($path4 . $filename); $image1->clear(); $image1->destroy(); unlink($file['tmp_name']); $this->_doc->setPhoto($filename); } }
public function resizeImage($source, $dest = null, $maxWidth = 0, $maxHeight = 0, $param = array()) { if (!($size = getimagesize($source))) { return null; } $width = $size[0]; $height = $size[1]; null === $dest ? $dest = $source : null; if (!$this->mkdirs(dirname($dest))) { return false; } if (isset($param['upload'])) { $maxWidth = $maxWidth ? $maxWidth : 10000; $maxHeight = $maxHeight ? $maxHeight : 10000; } else { $maxWidth = $maxWidth ? $maxWidth : $this->cfg['thumb']['maxwidth']; $maxHeight = $maxHeight ? $maxHeight : $this->cfg['thumb']['maxheight']; } $param['gd'] = 'gd' == $this->cfg['thumb']['method'] ? true : false; $param['crop'] = isset($param['crop']) ? $param['crop'] : $this->cfg['thumb']['crop']; $param['quality'] = $this->cfg['thumb']['jpg_quality']; $src_x = $src_y = 0; if ($size[0] <= $maxWidth && $size[1] <= $maxHeight) { $width = $size[0]; $height = $size[1]; if (isset($param['upload'])) { return copy($source, $dest); } else { return array_merge($size, array('min' => true)); } } else { $width = $maxWidth; $height = $maxHeight; if (!$height) { $ratio = $size[0] / $width; $height = $maxHeight = round($size[1] / $ratio); } $ratio_width = $size[0] / $maxWidth; $ratio_height = $size[1] / $maxHeight; if ($ratio_width < $ratio_height) { if ($param['crop']) { $src_y = ($size[1] - $maxHeight * $ratio_width) / 2; $size[1] = $maxHeight * $ratio_width; } else { $width = $size[0] / $ratio_height; $height = $maxHeight; } } else { if ($param['crop']) { $src_x = ($size[0] - $maxWidth * $ratio_height) / 2; $size[0] = $maxWidth * $ratio_height; } else { $width = $maxWidth; $height = $size[1] / $ratio_width; } } } if (!$param['gd'] && class_exists('Imagick')) { $img = new Imagick(); $img->readImage($source); $format = $this->_strtolower($img->getImageFormat()); if (!in_array($format, array('png', 'jpg', 'jpeg', 'gif')) || isset($param['setFormat']) && 'jpg' == $param['setFormat']) { $img->setCompression(Imagick::COMPRESSION_JPEG); $img->setCompressionQuality($param['quality']); $img->setImageFormat('jpeg'); $dest = $this->_substr($dest, 0, $this->_strrpos($dest, '.')); $dest .= '.jpg'; } //$img->resizeImage($width, $height, Imagick::FILTER_GAUSSIAN, 1); $param['crop'] ? $img->cropThumbnailImage($width, $height) : $img->resizeImage($width, $height, Imagick::FILTER_GAUSSIAN, 1); $img->writeImage($dest); $img->clear(); $img->destroy(); } else { $rgb = 0xffffff; $format = $this->_strtolower($this->_substr($size['mime'], $this->_strpos($size['mime'], '/') + 1)); $icfunc = 'imagecreatefrom' . $format; if (!function_exists($icfunc)) { return null; } $imgFrom = $icfunc($source); $img = imagecreatetruecolor($width, $height); imagefill($img, 0, 0, $rgb); //imagealphablending($img, false); //imagesavealpha($img, true); //$transparent = imagecolorallocatealpha($img, 255, 255, 255, 127); //imagefill($img, 0, 0, $transparent); imagecopyresampled($img, $imgFrom, 0, 0, $src_x, $src_y, $width, $height, $size[0], $size[1]); if ('png' == $format) { //imagepng($thum_img, $thum_fname, $quality, PNG_ALL_FILTERS); imagejpeg($img, $dest, $param['quality']); } else { imagejpeg($img, $dest, $param['quality']); } imagedestroy($imgFrom); imagedestroy($img); } return $size; }
/** * Outputs an image resource as a given type * * @internal Imagick::INTERLACE_[GIF|JPEG|PNG] require Imagick compiled against ImageMagick 6.3.4+ * * @param Imagick $im * @param string $type * @param string $filename * @param int $qual * @throws ImagickException * @return bool */ function zp_imageOutput($im, $type, $filename = NULL, $qual = 75) { global $_imagemagick_version, $_imagick_newer_interlace; if (!isset($_imagick_newer_interlace)) { $_imagick_newer_interlace = version_compare($_imagemagick_version['versionNumber'], '6.3.4', '>='); } $interlace = getOption('image_interlace'); $qual = max(min($qual, 100), 0); $im->setImageFormat($type); switch ($type) { case 'gif': $im->setCompression(Imagick::COMPRESSION_LZW); $im->setCompressionQuality($qual); if ($interlace) { if ($_imagick_newer_interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_GIF); } else { $im->setInterlaceScheme(Imagick::INTERLACE_LINE); } } break; case 'jpeg': case 'jpg': $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality($qual); if ($interlace) { if ($_imagick_newer_interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_JPEG); } else { $im->setInterlaceScheme(Imagick::INTERLACE_LINE); } } break; case 'png': $im->setCompression(Imagick::COMPRESSION_ZIP); $im->setCompressionQuality($qual); if ($interlace) { if ($_imagick_newer_interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_PNG); } else { $im->setInterlaceScheme(Imagick::INTERLACE_LINE); } } break; } try { $im->optimizeImageLayers(); } catch (ImagickException $e) { if (DEBUG_IMAGE) { debugLog('Caught ImagickException in zp_imageOutput(): ' . $e->getMessage()); } } if ($filename == NULL) { header('Content-Type: image/' . $type); return print $im->getImagesBlob(); } return $im->writeImages($filename, true); }
public function getPreview($new_w = 200, $new_h = 200) { if ($this->hasPreview() && file_exists($this->getFullURI())) { $image = new Imagick($this->getFullURI()); if ($this->getMimeType() == 'application/pdf') { // Display page 1 of pdfs $image->setIteratorIndex(0); } $image->thumbnailImage($new_w, $new_h, true); $image->setImageFormat("png"); $image->setCompression(Imagick::COMPRESSION_LZW); $image->setCompressionQuality(90); return $image->getImageBlob(); } }