public function index() { $ps = array(); $user = $this->session->all_userdata(); if (isset($_POST['submit']) && isset($user) && isset($user['users_id']) && isset($_FILES['uploaded_image']['tmp_name'])) { $imageFile = time() . '.' . end(explode(".", $_FILES['uploaded_image']['name'])); $photoData = $_POST['photo']; $image = new Imagick($_FILES['uploaded_image']['tmp_name']); $height = $image->getImageHeight(); $width = $image->getImageWidth(); if ($width > 800 || $height > 800) { if ($height < $width) { $image->scaleImage(800, 0); } else { $image->scaleImage(0, 600); } } $image->writeImage('./storage/photos/b/' . $imageFile); $image->cropThumbnailImage(100, 100); $image->writeImage('./storage/thumbs/' . $imageFile); $ps['photo_b'] = '/storage/photos/b/' . $imageFile; $ps['thumb'] = '/storage/thumbs/' . $imageFile; $data = array('iname' => $photoData['iname'] ? $photoData['iname'] : 'noname', 'idesc' => $photoData['idesc'] ? $photoData['idesc'] : '', 'path' => '/storage/photos/', 'file' => $imageFile, 'thumb' => $ps['thumb'], 'add_date' => time(), 'allow_comments' => isset($photoData['allow_comments']) ? 1 : 0, 'users_id' => $user['users_id']); $this->db->insert('photos', $data); $photos_id = $this->db->insert_id(); $this->load->model('m_users'); $this->load->model('m_logs'); $this->m_users->update(array('num_photos' => $user['num_photos'] + 1), $user['users_id']); $this->m_logs->add(array('users_id' => $user['users_id'], 'action' => 1, 'object_type' => 2, 'object_id' => $photos_id)); } $ps['_activeMenu'] = 'upload'; $this->tpl->view('frontend/upload/', $ps); }
static function copyResizedImage($inputFile, $outputFile, $width, $height = null, $crop = true) { if (extension_loaded('gd')) { $image = new GD($inputFile); if ($height) { if ($width && $crop) { $image->cropThumbnail($width, $height); } else { $image->resize($width, $height); } } else { $image->resize($width); } return $image->save($outputFile); } elseif (extension_loaded('imagick')) { $image = new \Imagick($inputFile); if ($height && !$crop) { $image->resizeImage($width, $height, \Imagick::FILTER_LANCZOS, 1, true); } else { $image->resizeImage($width, null, \Imagick::FILTER_LANCZOS, 1); } if ($height && $crop) { $image->cropThumbnailImage($width, $height); } return $image->writeImage($outputFile); } else { throw new HttpException(500, 'Please install GD or Imagick extension'); } }
function create_thumb($source_file, $thumb_file, $edge = THUMBNAIL_CROP_EDGE, &$src_w = NULL, &$src_h = NULL) { $composite_img = new Imagick($source_file); $blank_img = new Imagick(); $src_w = $composite_img->getImageWidth(); $src_h = $composite_img->getImageHeight(); if ($src_h > $edge && $src_w > $edge) { $composite_img->cropThumbnailImage($edge, $edge); $composite_img->setImageFormat('jpeg'); $composite_img->writeImage($thumb_file); $composite_img->clear(); $blank_img = $composite_img; } else { $blank_img->newImage($edge, $edge, new ImagickPixel('#DEF'), "jpg"); if ($src_w > $src_h) { $crop_x = $src_w / 2 - $edge / 2; $crop_y = 0; $offset_x = 0; $offset_y = $edge / 2 - $src_h / 2; } else { $crop_x = 0; $crop_y = $src_h / 2 - $edge / 2; $offset_x = $edge / 2 - $src_w / 2; $offset_y = 0; } $composite_img->cropImage($edge, $edge, $crop_x, $crop_y); $blank_img->compositeImage($composite_img, Imagick::COMPOSITE_OVER, $offset_x, $offset_y); $blank_img->setImageFormat('jpeg'); $blank_img->writeImage($thumb_file); $blank_img->clear(); } return $blank_img; }
private function thumbnailCreator($imageAddress, $targetDirectory, $targetName) { $config = $this->config; $image = new \Imagick($imageAddress); $image->cropThumbnailImage($config['general']['image_tumbnail_width'], $config['general']['image_tumbnail_height']); $image->writeImage($targetDirectory . "/thumb_" . $targetName); return "thumb_" . $targetName; }
function createThumbnail($field, $x, $y) { // Create entry for thumbnail. $thumb = $this->ref($field, 'link'); if (!$thumb->loaded()) { $thumb->set('filestore_volume_id', $this->get('filestore_volume_id')); $thumb->set('original_filename', 'thumb_' . $this->get('original_filename')); $thumb->set('filestore_type_id', $this->get('filestore_type_id')); $thumb['filename'] = $thumb->generateFilename(); } if (class_exists('\\Imagick', false)) { $image = new \Imagick($this->getPath()); //$image->resizeImage($x,$y,\Imagick::FILTER_LANCZOS,1,true); $image->cropThumbnailImage($x, $y); $this->hook("beforeThumbSave", array($thumb)); $image->writeImage($thumb->getPath()); } elseif (function_exists('imagecreatefromjpeg')) { list($width, $height, $type) = getimagesize($this->getPath()); ini_set("memory_limit", "1000M"); $a = array(null, 'gif', 'jpeg', 'png'); $type = @$a[$type]; if (!$type) { throw $this->exception('This file type is not supported'); } //saving the image into memory (for manipulation with GD Library) $fx = "imagecreatefrom" . $type; $myImage = $fx($this->getPath()); $thumbSize = $x; // only supports rectangles if ($x != $y && 0) { throw $this->exception('Model_Image currently does not support non-rectangle thumbnails with GD extension')->addMoreInfo('x', $x)->addMoreInfo('y', $y); } // calculating the part of the image to use for thumbnail if ($width > $height) { $y = 0; $x = ($width - $height) / 2; $smallestSide = $height; } else { $x = 0; $y = ($height - $width) / 2; $smallestSide = $width; } // copying the part into thumbnail $myThumb = imagecreatetruecolor($thumbSize, $thumbSize); imagecopyresampled($myThumb, $myImage, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide); //final output imagejpeg($myThumb, $thumb->getPath()); imageDestroy($myThumb); imageDestroy($myImage); } else { // No Imagemagick support. Ignore resize $thumb->import($this->getPath(), 'copy'); } $thumb->save(); // update size and chmod }
/** * Generate a thumbnail from an object and return the ID of the new object. * * @param string $id * @param int $width * @param int $height * * @return string */ public function generateThumbnail($id, $width, $height = null) { if ($height === null) { $height = $width; } $temp = $this->container->download($id); $img = new \Imagick($temp->getPath()); $img->cropThumbnailImage($width, $height); $img->writeImage(); return $this->container->upload($temp); }
function resize_image($file, $w, $h, $crop = FALSE) { // @param file, width, height, crop // Resize an image using Imagick $img = new Imagick($file); if ($crop) { $img->cropThumbnailImage($w, $h); } else { $img->thumbnailImage($w, $h, TRUE); } return $img; }
public function resize_crop($width, $height) { if (!$this->info['width'] || !$this->info['height']) { return; } //Crop every other image for ($r = 0; $r < count($this->image); $r++) { $this->image->nextImage(); $this->image->cropThumbnailImage($width, $height); } $this->info['width'] = $width; $this->info['height'] = $height; }
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); } }
private function background() { if ($this->config['method'] === 'image' && is_file($this->config['image'])) { $image = new \Imagick(); try { $image->readImage($this->config['image']); $image->setImageType(\Imagick::IMGTYPE_TRUECOLORMATTE); } catch (\ImagickException $e) { throw new Exception\NotSupportedException("Ivatar - ({$this->config['image']}) unable to open image."); } $image->cropThumbnailImage($this->options['size'], $this->options['size']); $this->ivatar->compositeImage($image, \Imagick::COMPOSITE_DEFAULT, 0, 0); } }
public function start() { $data['_activeMenu'] = 'admin'; ignore_user_abort(true); set_time_limit(0); $offset = 0; $limit = 10; $this->db->where('updated', 0); $this->db->where('is_deleted', 0); $query = $this->db->get('photos_il', $limit, $offset); $photos = $query->result_array(); while (count($photos) > 0) { foreach ($photos as $p) { $img = $p['img']; $imageFile = str_replace('http://photo.ilich.in.ua/upload/', '', $img); echo '<p>' . $imageFile . '</p>'; if (file_exists('./upload/' . $imageFile)) { $image = new Imagick('./upload/' . $imageFile); //$imageFile=time().'.'.end(explode(".", $_FILES['uploaded_image']['name'])); $height = $image->getImageHeight(); $width = $image->getImageWidth(); if ($width > 800 || $height > 800) { if ($height < $width) { $image->scaleImage(800, 0); } else { $image->scaleImage(0, 600); } } $image->writeImage('./storage_2/photos/b/' . $imageFile); $image->cropThumbnailImage(100, 100); $image->writeImage('./storage_2/thumbs/' . $imageFile); $this->db->where('phid', $p['phid']); $this->db->update('photos_il', array('updated' => 1)); } else { $this->db->where('phid', $p['phid']); $this->db->update('photos_il', array('is_deleted' => 1)); } } $this->db->where('updated', 0); $query = $this->db->get('photos_il', $limit, $offset); $photos = $query->result_array(); } //$this->tpl->view('backend/install/', $data); }
function createThumbnail($field, $x, $y) { // Create entry for thumbnail. $thumb = $this->ref($field, 'link'); if (!$thumb->loaded()) { $thumb->set('filestore_volume_id', $this->get('filestore_volume_id')); $thumb->set('original_filename', 'thumb_' . $this->get('original_filename')); $thumb->set('filestore_type_id', $this->get('filestore_type_id')); $thumb['filename'] = $thumb->generateFilename(); } if (class_exists('\\Imagick', false)) { $image = new \Imagick($this->getPath()); //$image->resizeImage($x,$y,\Imagick::FILTER_LANCZOS,1,true); $image->cropThumbnailImage($x, $y); $this->hook("beforeThumbSave", array($thumb)); $image->writeImage($thumb->getPath()); } else { // No Imagemagick support. Ignore resize $thumb->import($this->getPath(), 'copy'); } $thumb->save(); // update size and chmod }
(isset($_POST['comment'])) ? $comment = $_POST['comment'] : $comment = ''; (isset($_POST['oldFileName'])) ? $oldFileName = $_POST['oldFileName'] : $oldFileName = '';*/ isset($_POST['newFileName']) ? $newFileName = $_POST['newFileName'] : ($newFileName = ''); isset($_POST['pureNewFileName']) ? $pureNewFileName = $_POST['pureNewFileName'] : ($pureNewFileName = ''); isset($_POST['fileType']) ? $fileType = $_POST['fileType'] : ($fileType = ''); isset($_POST['path']) ? $path = $_POST['path'] : ($path = ''); if (empty($path)) { $upath = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES['file']['name']; } else { $path = str_replace("/", DIRECTORY_SEPARATOR, $path); $upath = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . $path; } //echo $upath; $tempPath = $_FILES['file']['tmp_name']; $uploadPath = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $_FILES['file']['name']; //move_uploaded_file( $tempPath, $uploadPath ); move_uploaded_file($tempPath, $upath . $newFileName); $thumb = new Imagick($upath . $newFileName); //if($fileType != 'jpg') // $thumb->writeImage($upath . $pureNewFileName . '.jpg'); $thumb->cropThumbnailImage(160, 90); $thumb->setImageFormat('jpeg'); $thumb->writeImage($upath . '_thumbs' . DIRECTORY_SEPARATOR . 't_' . $pureNewFileName . '.jpg'); $thumb->destroy(); exec("C:\\ImageMagick\\convert.exe " . $upath . $newFileName . " -resize \"1024x1024>\" " . $upath . $pureNewFileName . "_1024.jpg"); $answer = array('answer' => 'File transfer completed'); $json = json_encode($answer); echo $json; } else { echo 'No files'; }
color: #337372; text-decoration: none; } </style> </head> <body>'; if (class_exists('Imagick')) { foreach (glob("*.*") as $filename) { if (!file_exists('thumb')) { mkdir('thumb'); } if (!file_exists('thumb/' . $filename) && in_array(end(explode('.', $filename)), $allowed_filetypes)) { $imagick = new Imagick($filename); $imagick->thumbnailImage(null, 100); $imagick->cropThumbnailImage(100, 100); $imagick->writeImage('thumb/' . $filename); $imagick->clear(); $imagick->destroy(); print '<img src="thumb/' . urlencode($filename) . '" alt="" class="thumb" data-filename="' . urlencode($filename) . '" />'; } elseif (in_array(end(explode('.', $filename)), $allowed_filetypes)) { print '<img src="thumb/' . urlencode($filename) . '" alt="" class="thumb" data-filename="' . urlencode($filename) . '" />'; } } foreach (glob("thumb/*.*") as $filename) { if (!file_exists(basename($filename))) { unlink($filename); } } } else { print '
/** * 生成制定(格式)大小的缩略图 */ public static function createThumb_by_type($file_name, $type) { $image = new Imagick($file_name); //缩放 if ($type == 80) { $image->cropThumbnailImage(80, 80); } else { if ($type == 120) { $image->cropThumbnailImage(120, 120); } else { if ($type == 480) { //480 保留EXIF 信息 $image->resizeImage(480, 480, 0, 1, true); } else { //判断大小 $img_w_h = Image::getImagesWidthHight($file_name); $width = $img_w_h['width']; $height = $img_w_h['height']; $fitbyWidth = $width >= $height ? true : false; if ($fitbyWidth) { $image->thumbnailImage($type, 0, false); } else { $image->thumbnailImage(0, $type, false); } } } } //缩略图路径文件名 $thumb_path = Image::getThumbName($file_name, $type); //缩放 //$image->resizeImage($type, $type, 0, 1, true); //写缩略图 $image->writeImage($thumb_path); return $thumb_path; }
$image = new Imagick($image_temp); $success = $image->cropImage($max_image_size, $max_image_size, 0, 0); if (!$success) { create_error($access_token, 'PHP', 'create_artist_img.php', 'Fail to crop the image.', $db); die('Fail to crop the image.'); } else { //Upload the image $image_save_folder = $destination_folder . $galleryDirectory . $imgName . '.' . $image_extension; $success = $image->writeImage($image_save_folder); if (!$success) { create_error($access_token, 'PHP', 'create_artist_img.php', 'Fail to upload the image.', $db); die('Fail to upload the image.'); } else { chmod($image_save_folder, 0644); //Create the thumbnail image $success = $image->cropThumbnailImage($max_thumb_size, $max_thumb_size); if (!$success) { create_error($access_token, 'PHP', 'create_artist_img.php', 'Fail to crop the image thumbnail.', $db); die('Fail to crop the image thumbnail.'); } else { //Upload the thumbnail image $thumb_save_folder = $destination_folder . $galleryDirectory . $imgName . $thumb_suffix . '.' . $image_extension; $success = $image->writeImage($thumb_save_folder); if (!$success) { create_error($access_token, 'PHP', 'create_artist_img.php', 'Fail to upload the image thumbnail.', $db); die('Fail to upload the image thumbnail.'); } chmod($thumb_save_folder, 0644); $result_artist_imgOverviewPath = mysql_query("select img from artist where gallery_id = '" . $galleryId . "' and id = '" . $artistId . "'", $db); while ($row = mysql_fetch_array($result_artist_imgOverviewPath, MYSQL_ASSOC)) { $imgOverview = getImgOverviewPath($destination_folder . $galleryDirectory, utf8_encode($row['img']));
/** * @param $srcImagePath * @param bool $preset * @return string Path to cached file * @throws \Exception */ public function createCachedFile($srcImagePath, $preset = false) { if (!$preset) { $preset = $this->defaultSize; } $fileExtension = pathinfo($srcImagePath, PATHINFO_EXTENSION); $fileName = pathinfo($srcImagePath, PATHINFO_FILENAME); $pathToSave = $this->cachePath . '/' . $preset . '/' . $fileName . '.' . $fileExtension; BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true); $size = $preset ? $this->parseSize($preset) : false; // if($this->graphicsLibrary == 'Imagick'){ $image = new \Imagick($srcImagePath); $image->setImageCompressionQuality(30); if ($size) { if ($size['height'] && $size['width']) { $image->cropThumbnailImage($size['width'], $size['height']); } elseif ($size['height']) { $image->thumbnailImage(0, $size['height']); } elseif ($size['width']) { $image->thumbnailImage($size['width'], 0); } else { throw new \Exception('Error at $this->parseSize($sizeString)'); } } $image->writeImage($pathToSave); // } if (!is_file($pathToSave)) { throw new \Exception('Error while creating cached file'); } return $image; }
/** * Crop center & resize the image * * @param \Imagick image * @param integer width * @param integer Height */ public function cropCenter(\Imagick $image, $width, $height) { $image->cropThumbnailImage($width, $height); $image->unsharpMaskImage(0 , 0.5 , 1 , 0.05); }
/** * @param int $thumbSize * @return null|string * @throws \Exception */ public function getThumb($thumbSize = Image::SMALL_THUMB) { switch ($this->type) { case self::IMAGE_FILETYPE: $ext = $this->getExtension(); $imageId = $this->getId(); $urlPart = Image::imgPath($thumbSize, $imageId, $ext, FileService::FROM_PUBLIC); if (!file_exists($urlPart)) { $originalLocation = $this->getLocation(); $image = new \Imagick($originalLocation); $size = Image::sizeByType($thumbSize); $image->cropThumbnailImage($size['width'], $size['height']); FileService::prepareDir(FileService::PUBLIC_PATH . $urlPart); $image->writeimage(FileService::PUBLIC_PATH . $urlPart); } return $urlPart; case self::AUDIO_FILETYPE: return Audio::audioPath($this->id, $this->getExtension(), FileService::FROM_PUBLIC); case self::VIDEO_FILETYPE: return Video::videoPath($this->id, $this->getExtension(), FileService::FROM_PUBLIC); default: } return null; }
function resizeCut($w, $h) { if ($this->image_type != 'GIF') { $this->image->cropThumbnailImage($w, $h); } else { $color_transparent = new ImagickPixel("transparent"); //透明色 $dest = new Imagick(); foreach ($this->image as $frame) { $page = $frame->getImagePage(); $tmp = new Imagick(); $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif'); $tmp->compositeImage($frame, Imagick::COMPOSITE_OVER, $page['x'], $page['y']); $tmp->cropThumbnailImage($w, $h); $dest->addImage($tmp); $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0); $dest->setImageDelay($frame->getImageDelay()); $dest->setImageDispose($frame->getImageDispose()); } $dest->coalesceImages(); $this->image->destroy(); $this->image = $dest; } }
break; default: $cq = 100; break; } $image->setImageFormat('jpeg'); $image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality($cq); } else { $image->setImageFormat('png'); $compress[] = $file; } if (isset($size[SPLASH_ROTATE])) { $image->rotateImage(new ImagickPixel('none'), $size[SPLASH_ROTATE]); } $image->cropThumbnailImage($size[SPLASH_WIDTH], $size[SPLASH_HEIGHT]); $image->setImageResolution($size[SPLASH_DPI], $size[SPLASH_DPI]); $image->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH); $image->writeImage($file); } } if ($_POST['compression'] && count($compress) > 0) { switch ($_POST['compression']) { case 'low': $o = 1; break; case 'medium': $o = 2; break; case 'high': $o = 3;
/** * Method to create a thumbnail for an image * * @param $srcPath The original source of the image. * @param $destPath The destination path for the image * @param $destType The destination image type. * @param $destWidth The width of the thumbnail. * @param $destHeight The height of the thumbnail. * * @return bool True on success. */ public static function createThumb($srcPath, $destPath, $destType, $destWidth = 64, $destHeight = 64) { // Get the image size for the current original photo list($currentWidth, $currentHeight) = getimagesize($srcPath); $config = CFactory::getConfig(); $jconfig = JFactory::getConfig(); // Find the correct x/y offset and source width/height. Crop the image squarely, at the center. if ($currentWidth == $currentHeight) { $sourceX = 0; $sourceY = 0; } else { if ($currentWidth > $currentHeight) { //$sourceX = intval( ( $currentWidth - $currentHeight ) / 2 ); $sourceX = 0; /* HTGMOD */ $sourceY = 0; $currentWidth = $currentHeight; } else { $sourceX = 0; $sourceY = intval(($currentHeight - $currentWidth) / 2); $currentHeight = $currentWidth; } } $imageEngine = $config->get('imageengine'); $magickPath = $config->get('magickPath'); // Use imageMagick if available if (class_exists('Imagick') && ($imageEngine == 'auto' || $imageEngine == 'imagick')) { // Put the new image in temporary dest path, and move them using // Joomla API to ensure new folder is created $tempFilename = $jconfig->getValue('tmp_path') . DS . md5($destPath); $thumb = new Imagick(); $thumb->readImage($srcPath); $thumb->cropThumbnailImage($destWidth, $destHeight); $thumb->writeImage($tempFilename); $thumb->clear(); $thumb->destroy(); // Move to the correct path JFile::move($tempFilename, $destPath); return true; } else { if (!empty($magickPath) && !class_exists('Imagick')) { // Execute the command to resize. In windows, the commands are executed differently. if (JString::strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $file = rtrim($config->get('magickPath'), '/') . DS . 'convert.exe'; $command = '"' . rtrim($config->get('magickPath'), '/') . DS . 'convert.exe"'; } else { $file = rtrim($config->get('magickPath'), '/') . DS . 'convert'; $command = '"' . rtrim($config->get('magickPath'), '/') . DS . 'convert"'; } if (JFile::exists($file) && function_exists('exec')) { $execute = $command . ' -resize ' . $destWidth . 'x' . $destHeight . ' ' . $srcPath . ' ' . $destPath; exec($execute); // Test if the files are created, otherwise we know the exec failed. if (JFile::exists($destPath)) { return true; } } } } // IF all else fails, we try to use GD return CImageHelper::resize($srcPath, $destPath, $destType, $destWidth, $destHeight, $sourceX, $sourceY, $currentWidth, $currentHeight); }
public function createVersion($imagePath, $sizeString = false) { if (strlen($this->urlAlias) < 1) { throw new \Exception('Image without urlAlias!'); } $cachePath = $this->getModule()->getCachePath(); $subDirPath = $this->getSubDur(); $fileExtension = pathinfo($this->filePath, PATHINFO_EXTENSION); if ($sizeString) { $sizePart = '_' . $sizeString; } else { $sizePart = ''; } $pathToSave = $cachePath . '/' . $subDirPath . '/' . $this->urlAlias . $sizePart . '.' . $fileExtension; BaseFileHelper::createDirectory(dirname($pathToSave), 0777, true); if ($sizeString) { $size = $this->getModule()->parseSize($sizeString); } else { $size = false; } if ($this->getModule()->graphicsLibrary == 'Imagick') { $image = new \Imagick($imagePath); $image->setImageCompressionQuality(100); if ($size) { if ($size['height'] && $size['width']) { $image->cropThumbnailImage($size['width'], $size['height']); } elseif ($size['height']) { $image->thumbnailImage(0, $size['height']); } elseif ($size['width']) { $image->thumbnailImage($size['width'], 0); } else { throw new \Exception('Something wrong with this->module->parseSize($sizeString)'); } } $image->writeImage($pathToSave); } else { $image = new \abeautifulsite\SimpleImage($imagePath); if ($size) { if ($size['height'] && $size['width']) { //$image->thumbnail($size['width'], $size['height']); $image->best_fit($size['width'], $size['height']); } elseif ($size['height']) { $image->fit_to_height($size['height']); } elseif ($size['width']) { $image->fit_to_width($size['width']); } else { throw new \Exception('Something wrong with this->module->parseSize($sizeString)'); } } //WaterMark if ($this->getModule()->waterMark) { if (!file_exists(Yii::getAlias($this->getModule()->waterMark))) { throw new Exception('WaterMark not detected!'); } $wmMaxWidth = intval($image->get_width() * 0.4); $wmMaxHeight = intval($image->get_height() * 0.4); $waterMarkPath = Yii::getAlias($this->getModule()->waterMark); $waterMark = new \abeautifulsite\SimpleImage($waterMarkPath); if ($waterMark->get_height() > $wmMaxHeight or $waterMark->get_width() > $wmMaxWidth) { $waterMarkPath = $this->getModule()->getCachePath() . DIRECTORY_SEPARATOR . pathinfo($this->getModule()->waterMark)['filename'] . $wmMaxWidth . 'x' . $wmMaxHeight . '.' . pathinfo($this->getModule()->waterMark)['extension']; //throw new Exception($waterMarkPath); if (!file_exists($waterMarkPath)) { $waterMark->fit_to_width($wmMaxWidth); $waterMark->save($waterMarkPath, 100); if (!file_exists($waterMarkPath)) { throw new Exception('Cant save watermark to ' . $waterMarkPath . '!!!'); } } } $image->overlay($waterMarkPath, 'bottom right', 0.5, -10, -10); } $image->save($pathToSave, 100); } return $image; }
if ($_FILES['file']['name'] != "") { // El campo foto contiene una imagen... // Primero, hay que validar que se trata de un JPG/GIF/PNG $allowedExts = array("jpg", "jpeg", "gif", "png", "JPG", "GIF", "PNG"); $ext = end(explode(".", $_FILES["file"]["name"])); if (($_FILES["file"]["type"] == "image/gif" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/png" || $_FILES["file"]["type"] == "image/pjpeg") && in_array($ext, $allowedExts)) { $ext = end(explode('.', $_FILES['file']['name'])); $photo = substr(md5(uniqid(rand())), 0, 10) . "." . $ext; $dir = dirname(__FILE__) . '/../../public/img/users'; // directorio de tu elección if (move_uploaded_file($_FILES['file']['tmp_name'], $dir . '/' . $photo)) { $user = User::find($data['user']['id']); $user->img = "img/users/" . $photo; $user->save(); $img = new Imagick($dir . '/' . $photo); $img->cropThumbnailImage(50, 50); $img->writeImage($dir . '/' . $photo); $results['img'] = "img/users/" . $photo; $results["success"] = "true"; } } else { $results["error"] = "Invalid format"; } } else { $results["error"] = "Not exist file"; } } else { $results["success"] = "false"; $results["error"] = "No auth"; } echo json_encode($results);
function uplUtil($path, $width, $height, $htmlAttributes = array(), $return = false) { $types = array(1 => "gif", "jpeg", "png", "swf", "psd", "wbmp"); // used to determine image type if (empty($htmlAttributes['alt'])) { $htmlAttributes['alt'] = 'thumb'; } // Put alt default $fullpath = TMP; $url = $fullpath . $path; if (!($size = getimagesize($url))) { return; } // image doesn't exist $fp = WWW_ROOT . 'img' . DS; $relfile = $this->request->webroot . DS . 'img' . '/' . $this->cacheDir . '/' . $width . 'x' . $height . '_' . basename($path); // relative file $cachefile = $fp . $this->cacheDir . DS . $width . 'x' . $height . '_' . basename($path); // location on server if (file_exists($cachefile)) { $csize = getimagesize($cachefile); $cached = $csize[0] == $width && $csize[1] == $height; // image is cached if (@filemtime($cachefile) < @filemtime($url)) { // check if up to date $cached = false; } } else { $cached = false; } if (!$cached) { $resize = $size[0] > $width || $size[1] > $height || ($size[0] < $width || $size[1] < $height); } else { $resize = false; } if ($resize) { $image = new Imagick($url); $image->cropThumbnailImage($width, $height); // Crop image and thumb $image->writeImage($cachefile); } elseif (!$cached) { copy($url, $cachefile); } return $this->Html->image($relfile, $htmlAttributes); }
/** * Creates a new image given an original path, a new path, a target width and height. * Optionally crops image to exactly match given width and height. * @param string $originalPath The path to the original image * @param string $newpath The path to the new image to be created * @param int $width The maximum width of the new image * @param int $height The maximum height of the new image * @param bool $crop = false Set to true to resize and crop the image, set to false to just resize the image * @return bool * @example Resizing from 200x200 to 100x50 with $crop = false will result in a 50 x 50 image (same aspect ratio as source, scaled down to a quarter of size) * @example Resizing from 200x200 to 100x50 with $crop = true will result in a 100 x 50 image (same aspect ratio as source, scaled down to a half of size and cropped in height) * @example Resizing from 200x200 to 1000x1000 with either $crop = false or $crop = true in a copy of the original image (200x200) */ public function create($originalPath, $newPath, $width, $height, $crop = false) { // first, we grab the original image. We shouldn't ever get to this function unless the image is valid $imageSize = @getimagesize($originalPath); if ($imageSize === false) { return false; } $oWidth = $imageSize[0]; $oHeight = $imageSize[1]; $finalWidth = 0; //For cropping, this is really "scale to width before chopping extra height" $finalHeight = 0; //For cropping, this is really "scale to height before chopping extra width" $do_crop_x = false; $do_crop_y = false; $crop_src_x = 0; $crop_src_y = 0; // first, if what we're uploading is actually smaller than width and height, we do nothing if ($oWidth < $width && $oHeight < $height) { $finalWidth = $oWidth; $finalHeight = $oHeight; $width = $oWidth; $height = $oHeight; } else { if ($crop && ($height >= $oHeight && $width <= $oWidth)) { //crop to width only -- don't scale anything $finalWidth = $oWidth; $finalHeight = $oHeight; $height = $oHeight; $do_crop_x = true; } else { if ($crop && ($width >= $oWidth && $height <= $oHeight)) { //crop to height only -- don't scale anything $finalHeight = $oHeight; $finalWidth = $oWidth; $width = $oWidth; $do_crop_y = true; } else { // otherwise, we do some complicated stuff // first, we divide original width and height by new width and height, and find which difference is greater $wDiff = $oWidth / $width; $hDiff = $height != 0 ? $oHeight / $height : 0; if (!$crop && $wDiff > $hDiff) { //no cropping, just resize down based on target width $finalWidth = $width; $finalHeight = $wDiff != 0 ? $oHeight / $wDiff : 0; } else { if (!$crop) { //no cropping, just resize down based on target height $finalWidth = $hDiff != 0 ? $oWidth / $hDiff : 0; $finalHeight = $height; } else { if ($crop && $wDiff > $hDiff) { //resize down to target height, THEN crop off extra width $finalWidth = $hDiff != 0 ? $oWidth / $hDiff : 0; $finalHeight = $height; $do_crop_x = true; } else { if ($crop) { //resize down to target width, THEN crop off extra height $finalWidth = $width; $finalHeight = $wDiff != 0 ? $oHeight / $wDiff : 0; $do_crop_y = true; } } } } } } } //Calculate cropping to center image if ($do_crop_x) { /* //Get half the difference between scaled width and target width, // and crop by starting the copy that many pixels over from the left side of the source (scaled) image. $nudge = ($width / 10); //I have *no* idea why the width isn't centering exactly -- this seems to fix it though. $crop_src_x = ($finalWidth / 2.00) - ($width / 2.00) + $nudge; */ $crop_src_x = round(($oWidth - $width * $oHeight / $height) * 0.5); } if ($do_crop_y) { /* //Calculate cropping... //Get half the difference between scaled height and target height, // and crop by starting the copy that many pixels down from the top of the source (scaled) image. $crop_src_y = ($finalHeight / 2.00) - ($height / 2.00); */ $crop_src_y = round(($oHeight - $height * $oWidth / $width) * 0.5); } $processed = false; if (class_exists('Imagick')) { try { $image = new Imagick(); $imageRead = false; if ($crop) { $image->setSize($finalWidth, $finalHeight); if ($image->readImage($originalPath) === true) { $image->cropThumbnailImage($width, $height); $imageRead = true; } } else { $image->setSize($width, $height); if ($image->readImage($originalPath) === true) { $image->thumbnailImage($width, $height, true); $imageRead = true; } } if ($imageRead) { if ($image->getCompression() == imagick::COMPRESSION_JPEG) { $image->setCompressionQuality($this->jpegCompression); } if ($image->writeImage($newPath) === true) { $processed = true; } } } catch (Exception $x) { } } if (!$processed) { //create "canvas" to put new resized and/or cropped image into if ($crop) { $image = @imageCreateTrueColor($width, $height); } else { $image = @imageCreateTrueColor($finalWidth, $finalHeight); } if ($image === false) { return false; } $im = false; switch ($imageSize[2]) { case IMAGETYPE_GIF: $im = @imageCreateFromGIF($originalPath); break; case IMAGETYPE_JPEG: $im = @imageCreateFromJPEG($originalPath); break; case IMAGETYPE_PNG: $im = @imageCreateFromPNG($originalPath); break; default: @imagedestroy($image); return false; } if ($im === false) { @imagedestroy($image); return false; } // Better transparency - thanks for the ideas and some code from mediumexposure.com if ($imageSize[2] == IMAGETYPE_GIF || $imageSize[2] == IMAGETYPE_PNG) { $trnprt_indx = imagecolortransparent($im); // If we have a specific transparent color if ($trnprt_indx >= 0 && $trnprt_indx < imagecolorstotal($im)) { // Get the original image's transparent color's RGB values $trnprt_color = imagecolorsforindex($im, $trnprt_indx); // Allocate the same color in the new image resource $trnprt_indx = imagecolorallocate($image, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']); // Completely fill the background of the new image with allocated color. imagefill($image, 0, 0, $trnprt_indx); // Set the background color for new image to transparent imagecolortransparent($image, $trnprt_indx); } else { if ($imageSize[2] == IMAGETYPE_PNG) { // Turn off transparency blending (temporarily) imagealphablending($image, false); // Create a new transparent color for image $color = imagecolorallocatealpha($image, 0, 0, 0, 127); // Completely fill the background of the new image with allocated color. imagefill($image, 0, 0, $color); // Restore transparency blending imagesavealpha($image, true); } } } $res = @imageCopyResampled($image, $im, 0, 0, $crop_src_x, $crop_src_y, $finalWidth, $finalHeight, $oWidth, $oHeight); @imagedestroy($im); if ($res === false) { @imagedestroy($image); return false; } $res2 = false; switch ($imageSize[2]) { case IMAGETYPE_GIF: $res2 = @imageGIF($image, $newPath); break; case IMAGETYPE_JPEG: $res2 = @imageJPEG($image, $newPath, $this->jpegCompression); break; case IMAGETYPE_PNG: $res2 = @imagePNG($image, $newPath); break; } @imagedestroy($image); if ($res2 === false) { return false; } } @chmod($newPath, FILE_PERMISSIONS_MODE); return true; }
if (class_exists("imagick")) { $type_image = "imagemagick"; //(common || imagemagick) } else { $type_image = "common"; //(common || imagemagick) } $root_path = substr($_SERVER['SCRIPT_FILENAME'], 0, strrpos($_SERVER['SCRIPT_FILENAME'], "/")); $filename = $root_path . "/store/" . $_GET["file"]; $width = 80; $height = 80; switch ($type_image) { case "imagemagick": $im = new Imagick($filename); $im->cropThumbnailImage($width, $height); header("Content-Type: image/jpg"); echo $im->getImageBlob(); break; case "common": cropImage_common($filename, $width, $height); break; } function cropImage_common($filename, $newWidth, $newHeight) { $originalFile = $filename; $info = getimagesize($originalFile); $mime = $info['mime']; switch ($mime) { case 'image/jpeg': $image_create_func = 'imagecreatefromjpeg';
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; }
/** * Ресайз картинки уже добавленной в webdav * * @param string $to Куда сохранить и с каким именем * @param integer $newWidth Ширина в пикселах * @param integer $newHeight Высота в пикселах * @param string $option Тип ресайза: portrait - приоритет высоты * landscape - приоритет ширины * crop - вырезание из центра картинки * auto - автоматический выбор * cropthumbnail - уменьшить и верезать по центру * @param boolean $savePngAlpha Сохранить альфа канал для PNG файлов * @return boolean true - рейсайз сделан, false - не сделан */ public function resizeImage($to, $newWidth, $newHeight, $option = "auto", $savePngAlpha = false, $table = null) { if (!in_array($this->image_size['type'], array(1, 2, 3))) { // Недопустимый формат файла return false; } $tmp_name = uniqid(); $file = "/tmp/{$tmp_name}"; file_put_contents($file, file_get_contents(WDCPREFIX_LOCAL . '/' . $this->path . $this->name)); /*switch($this->image_size['type']) { case 1: $img = imagecreatefromgif($file); break; case 2: $img = imagecreatefromjpeg($file); break; case 3: $img = imagecreatefrompng($file); break; default: $img = false; break; } if(!$img) { // Ошибка открытия файла return false; } // Расчитываем новые значения ширины и высоты картинки switch ($option) { case 'portrait': $optimalWidth = $this->_getImageSizeByFixedHeight($newHeight); $optimalHeight= $newHeight; break; case 'landscape': $optimalWidth = $newWidth; $optimalHeight= $this->_getImageSizeByFixedWidth($newWidth); break; case 'auto': $optionArray = $this->_getImageSizeByAuto($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; case 'crop': $optionArray = $this->_getImageOptimalCrop($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; } if ($this->image_size['type'] && $savePngAlpha) { $imageResized = $this->imageResizeAlpha($img, $optimalWidth, $optimalHeight); } else { $imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight); imagecopyresampled($imageResized, $img, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->image_size['width'], $this->image_size['height']); } if ($option == 'crop') { $cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 ); $cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 ); $crop = $imageResized; $imageResized = imagecreatetruecolor($newWidth , $newHeight); imagecopyresampled($imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight); } // Сохраняем измененную картинку $file = $file.'_resized'; switch($this->image_size['type']) { case 1: $ext = 'gif'; imagegif($imageResized, $file); break; case 2: $ext = 'jpg'; imagejpeg($imageResized, $file, $this->quality); break; case 3: $ext = 'png'; $scaleQuality = round(($this->quality/100) * 9); $invertScaleQuality = 9 - $scaleQuality; imagepng($imageResized, $file, $invertScaleQuality); break; }*/ switch ($option) { case 'portrait': $optimalWidth = $this->_getImageSizeByFixedHeight($newHeight); $optimalHeight = $newHeight; break; case 'landscape': $optimalWidth = $newWidth; $optimalHeight = $this->_getImageSizeByFixedWidth($newWidth); break; case 'auto': $optionArray = $this->_getImageSizeByAuto($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; case 'crop': $optionArray = $this->_getImageOptimalCrop($newWidth, $newHeight); $optimalWidth = $optionArray['optimalWidth']; $optimalHeight = $optionArray['optimalHeight']; break; } $imagick = new Imagick($file); if ($option == 'cropthumbnail') { $imagick->cropThumbnailImage($newWidth, $newHeight); } else { if ($option == 'crop') { $cropStartX = $optimalWidth / 2 - $newWidth / 2; $cropStartY = $optimalHeight / 2 - $newHeight / 2; $imagick->cropImage($newWidth, $newHeight, $cropStartX, $cropStartY); } else { if ($this->image_size['type'] == 1) { // GIF пытаемся сохранить анимацию при уменьшении изображения $imagick = $imagick->coalesceImages(); do { $imagick->scaleImage($optimalWidth, $optimalHeight, true); } while ($imagick->nextImage()); //$imagick->optimizeImageLayers(); } else { $imagick->scaleImage($optimalWidth, $optimalHeight, true); } } } //освобождаем память и сохраняем $imagick = $imagick->deconstructImages(); $imagick->writeImages($file, true); $tFile = new CFile(); if ($table) { $tFile->table = $table; } else { $tFile->table = $this->table; } $tFile->tmp_name = $file; $tFile->original_name = $this->original_name; $tFile->size = filesize($file); $tFile->path = dirname($to) . '/'; $tFile->name = basename($to); $tFile->_upload($file); return $tFile; }