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(); }
/** * 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; }
private function watermarkPrint_imagick($src, $watermark, $dest_x, $dest_y, $quality, $transparency, $watermarkImgInfo) { try { // Open the original image $img = new Imagick($src); // Open the watermark $watermark = new Imagick($watermark); // Set transparency if (strtoupper($watermark->getImageFormat()) !== 'PNG') { $watermark->setImageOpacity($transparency / 100); } // Overlay the watermark on the original image $img->compositeImage($watermark, imagick::COMPOSITE_OVER, $dest_x, $dest_y); // Set quality if (strtoupper($img->getImageFormat()) === 'JPEG') { $img->setImageCompression(imagick::COMPRESSION_JPEG); $img->setCompressionQuality($quality); } $result = $img->writeImage($src); $img->clear(); $img->destroy(); $watermark->clear(); $watermark->destroy(); return $result ? true : false; } catch (Exception $e) { return false; } }
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; }
/** * Displays image without saving and lose changes * * This method adds the Content-type HTTP header * * @param string type (JPG,PNG...); * @param int quality 75 * * @return bool|PEAR_Error TRUE or a PEAR_Error object on error * @access public */ function display($type = '', $quality = null) { $options = is_array($quality) ? $quality : array(); if (is_numeric($quality)) { $options['quality'] = $quality; } $quality = $this->_getOption('quality', $options, 75); $this->imagick->setImageCompression($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 { $image = $this->imagick->getImageBlob(); } catch (ImagickException $e) { return $this->raiseError('Could not display image.', IMAGE_TRANSFORM_ERROR_IO); } header('Content-type: ' . $this->getMimeType($type)); echo $image; $this->free(); return true; }
/** * 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 [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(); }
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; }
/** * 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; }
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; } }
/** * @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]); } }
/** * 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(); } } }
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; }
public function actionGo() { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { $f = $_POST['filter']; $capPhoto = $_POST['capPhoto']; $min_rand = rand(0, 1000); $max_rand = rand(100000000000, 10000000000000000); $name_file = rand($min_rand, $max_rand); //this part is for creating random name for image $ext = end(explode(".", $_FILES["file"]["name"])); //gets extension $file = Yii::app()->request->baseUrl . "photo/" . $name_file . "." . $ext; move_uploaded_file($_FILES["file"]["tmp_name"], Yii::app()->request->baseUrl . "photo/" . $name_file . "." . $ext); chmod($file, 0777); if (exif_imagetype($file) == IMAGETYPE_JPEG) { $exif = exif_read_data($file); if (isset($exif['Orientation'])) { $orientation = $exif['Orientation']; if ($orientation == 6) { $imz = new Imagick($file); $imz->rotateimage("#FFF", 90); $imz->writeImage($file); chmod($file, 0777); } else { if ($orientation == 8) { $imz = new Imagick($file); $imz->rotateimage("#FFF", -90); $imz->writeImage($file); chmod($file, 0777); } } } } // Max vert or horiz resolution $maxsize = 1200; // create new Imagick object $image = new Imagick($file); // Resizes to whichever is larger, width or height if ($image->getImageHeight() <= $image->getImageWidth()) { // Resize image using the lanczos resampling algorithm based on width $image->resizeImage($maxsize, 0, Imagick::FILTER_LANCZOS, 1); } else { // Resize image using the lanczos resampling algorithm based on height $image->resizeImage(0, $maxsize, Imagick::FILTER_LANCZOS, 1); } // Set to use jpeg compression $image->setImageCompression(Imagick::COMPRESSION_JPEG); // Set compression level (1 lowest quality, 100 highest quality) $image->setImageCompressionQuality(75); // Strip out unneeded meta data $image->stripImage(); // Writes resultant image to output directory $image->writeImage($file); // Destroys Imagick object, freeing allocated resources in the process $image->destroy(); chmod($file, 0777); $filter = Instagraph::factory($file, $file); $filter->{$f}(); // 320 Show Preview $immid = new Imagick($file); if ($immid->getimagewidth() > 320) { $immid->thumbnailImage(320, null); $immid->writeImage(Yii::app()->request->baseUrl . "thumb/thumb320_" . $name_file . "." . $ext); $immid->destroy(); chmod(Yii::app()->request->baseUrl . "thumb/thumb320_" . $name_file . "." . $ext, 0777); } else { $immid->writeImage(Yii::app()->request->baseUrl . "thumb/thumb320_" . $name_file . "." . $ext); $immid->destroy(); chmod(Yii::app()->request->baseUrl . "thumb/thumb320_" . $name_file . "." . $ext, 0777); } // null x 230 show last upload $imlast = new Imagick($file); $imlast->thumbnailimage(null, 230); $imlast->writeImage(Yii::app()->request->baseUrl . "thumb/thumb230_" . $name_file . "." . $ext); $imlast->destroy(); chmod(Yii::app()->request->baseUrl . "thumb/thumb230_" . $name_file . "." . $ext, 0777); // 130 x 110 thumbmail $im = new Imagick($file); $im->thumbnailImage(130, 110); $im->writeImage(Yii::app()->request->baseUrl . "thumb/thumb_" . $name_file . "." . $ext); chmod(Yii::app()->request->baseUrl . "thumb/thumb_" . $name_file . "." . $ext, 0777); $im->destroy(); $photo = new Photo(); $photo->link = $file; $photo->fbid = Yii::app()->facebook->getUser(); $photo->ip = $_SERVER['REMOTE_ADDR']; if ($photo->save()) { $id = $photo->id; if (isset($_POST['shareFB'])) { $share = 1; } else { $share = 0; } if ($share == 1) { $cr = "\n" . "http://www.pla2gram.com/?p=" . $id . "&theater=1"; $capFB = $capPhoto . $cr; // Post to Facebook $args = array('message' => $capFB); $args['image'] = '@' . realpath($file); Yii::app()->facebook->api('/me/photos', 'post', $args); Helper::redir("/?p=" . $id, 0); } else { Helper::redir("/?p=" . $id, 0); } } else { print_r($photo->getErrors()); } } }
switch ($_POST['compression']) { case 'low': $cq = 80; break; case 'medium': $cq = 65; break; case 'high': $cq = 50; 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) {
/** * Outputs an image resource as a given type * * @param Imagick $im * @param string $type * @param string $filename * @param int $qual * @return bool */ function zp_imageOutput($im, $type, $filename = NULL, $qual = 75) { $interlace = getOption('image_interlace'); $qual = max(min($qual, 100), 0); $im->setImageFormat($type); switch ($type) { case 'gif': $im->setImageCompression(Imagick::COMPRESSION_LZW); $im->setImageCompressionQuality($qual); if ($interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_GIF); } break; case 'jpeg': case 'jpg': $im->setImageCompression(Imagick::COMPRESSION_JPEG); $im->setImageCompressionQuality($qual); if ($interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_JPEG); } break; case 'png': $im->setImageCompression(Imagick::COMPRESSION_ZIP); $im->setImageCompressionQuality($qual); if ($interlace) { $im->setInterlaceScheme(Imagick::INTERLACE_PNG); } break; } $im->optimizeImageLayers(); if ($filename == NULL) { header('Content-Type: image/' . $type); return print $im->getImagesBlob(); } return $im->writeImages(imgSrcURI($filename), true); }
/** * */ function sharpen($path) { if (!class_exists('\\Imagick')) { return; } $dimensions = @getimagesize($path); if (!isset($dimensions[2]) || IMAGETYPE_JPEG != $dimensions[2]) { return; } debug("sharpening {$path}", 6); try { $imagick = new \Imagick($path); $imagick->unsharpMaskImage(0, 0.5, 1, 0); $imagick->setImageFormat("jpg"); $imagick->setImageCompression(\Imagick::COMPRESSION_JPEG); $imagick->setImageCompressionQuality(jpeg_quality()); $imagick->setInterlaceScheme(\Imagick::INTERLACE_PLANE); // this is for watermarking $imagick = \apply_filters("wp_resized2cache_imagick", $imagick, $path); $imagick->writeImage($path); $imagick->destroy(); } catch (Exception $e) { debug('something went wrong with imagemagick: ', $e->getMessage(), 4); return; } }
public static function createMedia($pack) { $pack->auth->permission = "read_write"; if (!users::authenticateUser($pack->auth)) { return new return_package(6, NULL, "Failed Authentication"); } $filenameext = strtolower(substr($pack->file_name, strrpos($pack->file_name, '.') + 1)); if ($filenameext == "jpeg") { $filenameext = "jpg"; } //sanity $filename = md5((string) microtime() . $pack->file_name); $newfilename = 'aris' . $filename . '.' . $filenameext; $resizedfilename = 'aris' . $filename . '_resized.' . $filenameext; $newthumbfilename = 'aris' . $filename . '_128.' . $filenameext; // Make sure playerUploaded requirements keep in sync with this list if ($filenameext != "jpg" && $filenameext != "png" && $filenameext != "gif" && $filenameext != "mp4" && $filenameext != "mov" && $filenameext != "m4v" && $filenameext != "3gp" && $filenameext != "caf" && $filenameext != "mp3" && $filenameext != "aac" && $filenameext != "m4a") { return new return_package(1, NULL, "Invalid filetype: '{$filenameext}'"); } $filefolder = ""; if ($pack->game_id) { $filefolder = $pack->game_id; } else { $filefolder = "players"; } $fspath = Config::v2_gamedata_folder . "/" . $filefolder . "/" . $newfilename; $resizedpath = Config::v2_gamedata_folder . "/" . $filefolder . "/" . $resizedfilename; $fsthumbpath = Config::v2_gamedata_folder . "/" . $filefolder . "/" . $newthumbfilename; $fp = fopen($fspath, 'w'); if (!$fp) { return new return_package(1, NULL, "Couldn't open file:{$fspath}"); } fwrite($fp, base64_decode($pack->data)); fclose($fp); $did_resize = false; if ($filenameext == "jpg" || $filenameext == "png" || $filenameext == "gif") { if (isset($pack->resize)) { $image = new Imagick($fspath); // Reorient based on EXIF tag switch ($image->getImageOrientation()) { case Imagick::ORIENTATION_UNDEFINED: // We assume normal orientation break; case Imagick::ORIENTATION_TOPLEFT: // All good break; case Imagick::ORIENTATION_TOPRIGHT: $image->flopImage(); break; case Imagick::ORIENTATION_BOTTOMRIGHT: $image->rotateImage('#000', 180); break; case Imagick::ORIENTATION_BOTTOMLEFT: $image->rotateImage('#000', 180); $image->flopImage(); break; case Imagick::ORIENTATION_LEFTTOP: $image->rotateImage('#000', 90); $image->flopImage(); break; case Imagick::ORIENTATION_RIGHTTOP: $image->rotateImage('#000', 90); break; case Imagick::ORIENTATION_RIGHTBOTTOM: $image->rotateImage('#000', -90); $image->flopImage(); break; case Imagick::ORIENTATION_LEFTBOTTOM: $image->rotateImage('#000', -90); break; } $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT); // Resize image proportionally so min(width, height) == $pack->resize $w = $image->getImageWidth(); $h = $image->getImageHeight(); if ($w < $h) { $image->resizeImage($pack->resize, $pack->resize / $w * $h, Imagick::FILTER_LANCZOS, 1); } else { $image->resizeImage($pack->resize / $h * $w, $pack->resize, Imagick::FILTER_LANCZOS, 1); } $image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(40); $image->writeImage($resizedpath); $did_resize = true; } $image = new Imagick(isset($pack->resize) ? $resizedpath : $fspath); //aspect fill to 128x128 $w = $image->getImageWidth(); $h = $image->getImageHeight(); if ($w < $h) { $image->thumbnailImage(128, 128 / $w * $h, 1, 1); } else { $image->thumbnailImage(128 / $h * $w, 128, 1, 1); } //crop around center $w = $image->getImageWidth(); $h = $image->getImageHeight(); $image->cropImage(128, 128, ($w - 128) / 2, ($h - 128) / 2); $image->writeImage($fsthumbpath); } if ($did_resize) { unlink($fspath); } // after making the 128 thumbnail $pack->media_id = dbconnection::queryInsert("INSERT INTO media (" . "file_folder," . "file_name," . (isset($pack->game_id) ? "game_id," : "") . (isset($pack->auth->user_id) ? "user_id," : "") . (isset($pack->name) ? "name," : "") . "created" . ") VALUES (" . "'" . $filefolder . "'," . "'" . ($did_resize ? $resizedfilename : $newfilename) . "'," . (isset($pack->game_id) ? "'" . addslashes($pack->game_id) . "'," : "") . (isset($pack->auth->user_id) ? "'" . addslashes($pack->auth->user_id) . "'," : "") . (isset($pack->name) ? "'" . addslashes($pack->name) . "'," : "") . "CURRENT_TIMESTAMP" . ")"); games::bumpGameVersion($pack); return media::getMedia($pack); }
/** * Apply transformations on image * * @param string $source Source image * @param array $params Transformations and parameters * @param string $store Temporary store on disk * * @return string */ public function transform($source, $params, $store = null) { try { $image = new \Imagick($source); $image->setImageCompression(\Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality($this->_quality); if (isset($params['negate'])) { $image->negateImage(false); } if (isset($params['rotate'])) { $image->rotateImage(new \ImagickPixel('#00000000'), $params['rotate']['angle']); } if (isset($params['crop'])) { $image->cropImage($params['crop']['w'], $params['crop']['h'], $params['crop']['x'], $params['crop']['y']); } if (isset($params['contrast'])) { $level = (int) $params['contrast']; if ($level < -10) { $level = -10; } else { if ($level > 10) { $level = 10; } } if ($level > 0) { for ($i = 0; $i < $level; $i++) { $image->contrastImage(1); } } else { if ($level < 0) { for ($i = $level; $i < 0; $i++) { $image->contrastImage(0); } } } } if (isset($params['brightness'])) { $value = (int) $params['brightness']; $brightness = null; if ($value <= 0) { $brightness = $value + 100; } else { $brightness = $value * 3 + 100; } $image->modulateImage($brightness, 100, 100); } $ret = null; if ($store !== null) { $ret = $image->writeImage($store); } else { $ret = $image->getImageBlob(); } $image->destroy(); return $ret; } catch (\ImagickException $e) { $image->destroy(); throw new \RuntimeException($e->getMessage()); } }
/** * Apply watermark to image. * * @param int $attachment_id Attachment ID * @param string $image_path Path to the file * @param string $image_size Image size * @param array $upload_dir Upload media data * @return void */ public function do_watermark( $attachment_id, $image_path, $image_size, $upload_dir ) { $options = apply_filters( 'iw_watermark_options', $this->options ); // get image mime type $mime = wp_check_filetype( $image_path ); // get watermark path $watermark_file = wp_get_attachment_metadata( $options['watermark_image']['url'], true ); $watermark_path = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $watermark_file['file']; // imagick extension if ( $this->extension === 'imagick' ) { // create image resource $image = new Imagick( $image_path ); // create watermark resource $watermark = new Imagick( $watermark_path ); // set transparency $image->setImageOpacity( round( 1 - (float)( $options['watermark_image']['transparent'] / 100 ), 2 ) ); // set compression quality if ( $mime['type'] === 'image/jpeg' ) { $image->setImageCompressionQuality( $options['watermark_image']['quality'] ); $image->setImageCompression( imagick::COMPRESSION_JPEG ); } else $image->setImageCompressionQuality( $options['watermark_image']['quality'] ); // set image output to progressive if ( $options['watermark_image']['jpeg_format'] === 'progressive' ) $image->setImageInterlaceScheme( Imagick::INTERLACE_PLANE ); // get image dimensions $image_dim = $image->getImageGeometry(); // get watermark dimensions $watermark_dim = $watermark->getImageGeometry(); // calculate watermark new dimensions list( $width, $height ) = $this->calculate_watermark_dimensions( $image_dim['width'], $image_dim['height'], $watermark_dim['width'], $watermark_dim['height'], $options ); // resize watermark $watermark->resizeImage( $width, $height, imagick::FILTER_CATROM, 1 ); // calculate image coordinates list( $dest_x, $dest_y ) = $this->calculate_image_coordinates( $image_dim['width'], $image_dim['height'], $width, $height, $options ); // combine two images together $image->compositeImage( $watermark, Imagick::COMPOSITE_OVERLAY, $dest_x, $dest_y, Imagick::CHANNEL_ALL ); // save watermarked image $image->writeImage( $image_path ); // clear image memory $image->clear(); $image->destroy(); $image = null; // clear watermark memory $watermark->clear(); $watermark->destroy(); $watermark = null; // gd extension } else { // get image resource $image = $this->get_image_resource( $image_path, $mime['type'] ); if ( $image !== false ) { // add watermark image to image $image = $this->add_watermark_image( $image, $options, $upload_dir ); if ( $image !== false ) { // save watermarked image $this->save_image_file( $image, $mime['type'], $image_path, $options['watermark_image']['quality'] ); // clear watermark memory imagedestroy( $image ); $image = null; } } } }
function LoadPhoto($cont, $idx) { $uploaddir = '../attached_file/'; $microtime = microtime(); $max_size = 5 * 1024 * 1024; $max_image_width = 5000; $max_image_height = 5000; $error = ''; $max_side_px = 800; $filetypes = array('image/jpeg'); //'image/png', 'image/bmp', 'image/gif' $extens = array('jpg', 'jpeg'); //'png', 'gif', 'bmp' $id_file = substr($microtime, 11) . substr($microtime, 2, 6); $ext = strtolower(substr($cont['name'], strrpos($cont['name'], ".") + 1)); if (is_uploaded_file($cont['tmp_name'])) { #Проверка веса if ($cont['size'] == 0) { $error = 'Файл 0кб.'; } elseif ($cont['size'] > $max_size) { $error = 'Размер превышает 5мб.'; } else { #Проверка типов if (in_array($cont['type'], $filetypes) and in_array($ext, $extens)) { $size = GetImageSize($cont['tmp_name']); #Проверка размера if ($size && $size[0] < $max_image_width && $size[1] < $max_image_height) { #Загрузка if (move_uploaded_file($cont['tmp_name'], $uploaddir . $id_file . '.' . $ext)) { $link = dbh::connect(); $sql = "INSERT INTO `attached_file` (id_file,ext,idx) VALUES('{$id_file}','{$ext}','{$idx}')"; $res = mysql_query($sql); dbh::disconnect($link); #Инициализируем максимальную сторону фотки, и принимаем решение делаем ли ресайз $x = $max_side_px; $y = $max_side_px; if ($size[0] > $size[1]) { $y = 0; } else { $x = 0; } $rex = $size[0] > $size[1] ? $size[0] : $size[1]; $rex = $rex > $max_side_px ? 1 : 0; #Фото без водяного знака, обрезаем большую сторону до 800, делает Quality=70% $img_no_mark = new Imagick($uploaddir . $id_file . '.' . $ext); $img_no_mark->setImageCompression(imagick::COMPRESSION_JPEG); $img_no_mark->setImageCompressionQuality(70); if ($rex) { $img_no_mark->scaleImage($x, $y); } $img_no_mark->writeImage($uploaddir . $id_file . '_s.' . $ext); $img_no_mark->destroy(); #Фото с водяным знаком, обрезаем большую сторону до 800 $img = new Imagick($uploaddir . $id_file . '.' . $ext); $mark = new Imagick($uploaddir . 'mark.png'); $rgs = new Imagick($uploaddir . 'rgs.png'); if ($rex) { $img->scaleImage($x, $y); } $w = $img->getImageWidth() - 371; $h = $img->getImageHeight() - 150; $wrgs = $img->getImageWidth() - 120; $hrgs = $h - 50; $textWrite = 'застраховано'; $wtxt = $img->getImageWidth() - 120; $htxt = $hrgs - 10; $fontColor = '#FFFFFF'; $fontSize = 18; $colorPix = new ImagickPixel($fontColor); $draw = new ImagickDraw(); $draw->setFontSize($fontSize); $draw->setFillColor($colorPix); $img->annotateImage($draw, $wtxt, $htxt, 0, $textWrite); $img->compositeImage($mark, imagick::COMPOSITE_OVER, $w, $h); $img->compositeImage($rgs, imagick::COMPOSITE_OVER, $wrgs, $hrgs); $img->writeImage($uploaddir . $id_file . '.' . $ext); #Так же делаем привью if ($size[0] > $size[1]) { $img->scaleImage(0, 150); } else { $img->scaleImage(150, 0); } $img->writeImage($uploaddir . $id_file . '_p.' . $ext); $img->destroy(); } else { $error = $cont['tmp_name'] . ' ' . $uploaddir . $id_file . $ext; } } else { $error = 'Превышен размер ' . $max_image_width . 'x' . $max_image_height . '.'; } } else { $error = 'Файл имеет недопустимый формат! Разрешены только jpg, jpeg.'; } } } else { $error = 'Файл пустой.'; } if ($error) { $error = 'Ошибка загрузки файла ' . $cont['name'] . '! ' . $error . '<br><br>'; } return $error; }
public static function thumbnail($item, $width = 0, $height = 0, $border = true, $ftname = '', $quality = 95, $scale_up_force = false) { if (is_numeric($item)) { $f = new file(); $f->load($item); $item = $f; } if (!get_class($item) == 'file') { return; } // precondition, the original image file must exist if (!file_exists($item->absolute_path()) || filesize($item->absolute_path()) < 1) { return; } $original = $item->absolute_path(); $thumbnail = ''; $item_id = $item->id; if (!empty($ftname)) { $item_id = $ftname; } else { if (!is_numeric($item_id)) { $item_id = md5($item->id); } } if ($border === true || $border === 'true' || $border === 1) { $border = 1; } else { $border = 0; } // do we have the thumbnail already created for this image? // option A) opaque JPEG FILE $thumbnail_path_jpg = NAVIGATE_PRIVATE . '/' . $item->website . '/thumbnails/' . $width . 'x' . $height . '-' . $border . '-' . $quality . '-' . $item_id . '.jpg'; if (file_exists($thumbnail_path_jpg)) { // ok, a file exists, but it's older than the image file? (original image file has changed) if (filemtime($thumbnail_path_jpg) > filemtime($original)) { // the thumbnail already exists and is up to date $thumbnail = $thumbnail_path_jpg; } } // option B) transparent PNG FILE $thumbnail_path_png = NAVIGATE_PRIVATE . '/' . $item->website . '/thumbnails/' . $width . 'x' . $height . '-' . $border . '-' . $item_id; if (file_exists($thumbnail_path_png)) { // ok, a file exists, but it's older than the image file? (original image file has changed) if (filemtime($thumbnail_path_png) > filemtime($original)) { // the thumbnail already exists and is up to date $thumbnail = $thumbnail_path_png; } } // do we have to create a new thumbnail if (empty($thumbnail) || isset($_GET['force']) || !(file_exists($thumbnail) && filesize($thumbnail) > 0)) { $thumbnail = $thumbnail_path_png; $handle = new upload($original); $size = array('width' => $handle->image_src_x, 'height' => $handle->image_src_y); $handle->image_convert = 'png'; $handle->file_max_size = '512M'; // maximum image size: 512M (it really depends on available memory) // if needed, calculate width or height with aspect ratio if (empty($width)) { if (!empty($size['height'])) { $width = round($height / $size['height'] * $size['width']); } else { $width = NULL; } return file::thumbnail($item, $width, $height, $border, $ftname); } else { if (empty($height)) { if (!empty($size['width'])) { $height = round($width / $size['width'] * $size['height']); } else { $height = NULL; } return file::thumbnail($item, $width, $height, $border, $ftname); } } $handle->image_x = $width; $handle->image_y = $height; if ($size['width'] < $width && $size['height'] < $height) { // the image size is under the requested width / height? => fill around with transparent color $handle->image_default_color = '#FFFFFF'; $handle->image_resize = true; $handle->image_ratio_no_zoom_in = true; $borderP = array(floor(($height - $size['height']) / 2), ceil(($width - $size['width']) / 2), ceil(($height - $size['height']) / 2), floor(($width - $size['width']) / 2)); $handle->image_border = $borderP; if ($scale_up_force) { $handle->image_border = array(); if ($height > width) { $handle->image_ratio_y = true; } else { $handle->image_ratio_x = true; } } $handle->image_border_color = '#FFFFFF'; $handle->image_border_opacity = 0; } else { // the image size is bigger than the requested width / height, we must resize it $handle->image_default_color = '#FFFFFF'; $handle->image_resize = true; $handle->image_ratio_fill = true; } if ($border == 0) { $handle->image_border = false; $handle->image_ratio_no_zoom_in = false; if (!empty($item->focalpoint) && $handle->image_src_x > 0) { $focalpoint = explode('#', $item->focalpoint); $crop = array('top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0); // calculate how the file will be scaled, by width or by height if ($handle->image_src_x / $handle->image_x > $handle->image_src_y / $handle->image_y) { // Y is ok, now crop extra space on X $ratio = $handle->image_y / $handle->image_src_y; $image_scaled_x = intval($handle->image_src_x * $ratio); $crop['left'] = max(0, round(($image_scaled_x * ($focalpoint[1] / 100) - $handle->image_x / 2) / $ratio)); $crop['right'] = max(0, round(($image_scaled_x * ((100 - $focalpoint[1]) / 100) - $handle->image_x / 2) / $ratio)); } else { // X is ok, now crop extra space on Y $ratio = $handle->image_x / $handle->image_src_x; $image_scaled_y = intval($handle->image_src_y * $ratio); $crop['top'] = max(0, round(($image_scaled_y * ($focalpoint[0] / 100) - $handle->image_y / 2) / $ratio)); $crop['bottom'] = max(0, round(($image_scaled_y * ((100 - $focalpoint[0]) / 100) - $handle->image_y / 2) / $ratio)); } $handle->image_precrop = array($crop['top'], $crop['right'], $crop['bottom'], $crop['left']); } $handle->image_ratio_crop = true; $handle->image_ratio_fill = true; } $handle->png_compression = 9; $handle->process(dirname($thumbnail)); rename($handle->file_dst_pathname, $thumbnail); clearstatcache(true, $thumbnail); if (!file_exists($thumbnail) || filesize($thumbnail) < 1) { return NULL; } // try to recompress the png thumbnail file to achieve the minimum file size, // only if some extra apps are available if (extension_loaded('imagick')) { $im = new Imagick($thumbnail); $image_alpha_range = $im->getImageChannelRange(Imagick::CHANNEL_ALPHA); //$image_alpha_mean = $im->getImageChannelMean(Imagick::CHANNEL_ALPHA); $image_is_opaque = $image_alpha_range['minima'] == 0 && $image_alpha_range['maxima'] == 0; // autorotate image based on EXIF data $im_original = new Imagick($original); $orientation = $im_original->getImageOrientation(); $im_original->clear(); switch ($orientation) { case imagick::ORIENTATION_BOTTOMRIGHT: $im->rotateimage(new ImagickPixel('transparent'), 180); // rotate 180 degrees break; case imagick::ORIENTATION_RIGHTTOP: $im->rotateimage(new ImagickPixel('transparent'), 90); // rotate 90 degrees CW break; case imagick::ORIENTATION_LEFTBOTTOM: $im->rotateimage(new ImagickPixel('transparent'), -90); // rotate 90 degrees CCW break; } // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! $im->setImageOrientation(imagick::ORIENTATION_TOPLEFT); if (!$image_is_opaque) { $im->setImageFormat('PNG32'); // Force a full RGBA image format with full semi-transparency. $im->setBackgroundColor(new ImagickPixel('transparent')); $im->setImageCompression(Imagick::COMPRESSION_UNDEFINED); $im->setImageCompressionQuality(0); $im->writeimage($thumbnail); } else { $im->setImageFormat('JPG'); // create an OPAQUE JPG file with the given quality (default 95%) $im->setImageCompressionQuality($quality); $im->writeimage($thumbnail_path_jpg); @unlink($thumbnail); $thumbnail = $thumbnail_path_jpg; } } /* if(command_exists('pngquant')) // PNG Optimization: 8 bit with transparency { @shell_exec('pngquant -s1 --ext .pngquant '.$thumbnail); if(file_exists($thumbnail.'.pngquant')) { unlink($thumbnail); rename($thumbnail.'.pngquant', $thumbnail); } } else*/ } clearstatcache(true, $thumbnail); return $thumbnail; }
/** * 使用Imagick重新绘制图片 * * @param string $p_sPath * @param int $p_iWidth * @param int $p_iHeight * @param string $p_sExtension * @param array $p_aOption * @return blob */ static function resizeImage_Imagick($p_sPath, $p_iWidth, $p_iHeight, $p_sExtension, $p_aOption = array()) { $oImage = new Imagick(); $oImage->readImage($p_sPath); $iOWidth = $oImage->getImageWidth(); $iOHeight = $oImage->getImageHeight(); if ($iOWidth < $p_iWidth and $iOHeight < $p_iHeight) { // 不做拉伸图片处理 $p_iWidth = $iOWidth; $p_iHeight = $iOHeight; } if (true === $p_aOption['bThumbnail']) { switch ($p_aOption['sMode']) { case 'cut': // 裁剪 $oImage->cropThumbnailImage($p_iWidth, $p_iHeight); break; case 'zoom': // 缩放 // 缩放 default: switch ($p_aOption['sZoomMode']) { case 'fill': // 填充 $oImage->thumbnailImage($p_iWidth, $p_iHeight); break; case 'scale': // 等比例缩放 // 等比例缩放 default: switch ($p_aOption['sZoomScaleMode']) { case 'width': $oImage->thumbnailImage($p_iWidth, round($p_iWidth * $iOHeight / $iOWidth), true); break; case 'height': $oImage->thumbnailImage(round($p_iHeight * $iOWidth / $iOHeight), $p_iHeight, true); break; case 'mix': default: $oImage->thumbnailImage($p_iWidth, $p_iHeight, true); break; } break; } break; } } else { switch ($p_aOption['sMode']) { case 'cut': $oImage->cropImage($p_iWidth, $p_iHeight, round(($iOWidth - $p_iWidth) / 2), round(($iOHeight - $p_iHeight) / 2)); break; case 'zoom': default: switch ($p_aOption['sZoomMode']) { case 'fill': $oImage->resizeImage($p_iWidth, $p_iHeight, Imagick::FILTER_CATROM, 1); break; case 'scale': default: switch ($p_aOption['sZoomScaleMode']) { case 'width': $oImage->resizeImage($p_iWidth, round($p_iWidth * $iOHeight / $iOWidth), Imagick::FILTER_CATROM, 1, true); break; case 'height': $oImage->resizeImage(round($p_iHeight * $iOWidth / $iOHeight), $p_iHeight, Imagick::FILTER_CATROM, 1, true); break; case 'mix': default: $oImage->resizeImage($p_iWidth, $p_iHeight, Imagick::FILTER_CATROM, 1, true); break; } break; } break; } } if (false !== $p_aOption['mWatermark']) { // 水印 $aWatermark = $p_aOption['mWatermark']; if (file_exists($aWatermark['sFilePath'])) { $oWaterMark = new Imagick(); $oWaterMark->readImage($aWatermark['sFilePath']); $aEdge = $aWatermark['aEdge']; if (isset($aEdge['iLeft'])) { $iPosX = $aEdge['iLeft']; } elseif (isset($aEdge['iRight'])) { $iPosX = $oImage->getImageWidth() - $oWaterMark->getImageWidth() - $aEdge['iRight']; } else { throw new Exception(__CLASS__ . ': configuration(resize_watermark_edge) lost.'); return false; } if (isset($aEdge['iUp'])) { $iPosY = $aEdge['iUp']; } elseif (isset($aEdge['iDown'])) { $iPosY = $oImage->getImageHeight() - $oWaterMark->getImageHeight() - $aEdge['iDown']; } else { throw new Exception(__CLASS__ . ': configuration(resize_watermark_edge) lost.'); return false; } $oImage->compositeImage($oWaterMark, Imagick::COMPOSITE_DEFAULT, $iPosX, $iPosY); $oWaterMark->clear(); $oWaterMark->destroy(); } else { throw new Exception(__CLASS__ . ': configuration(resize_watermark_path) lost.'); return false; } } $oImage->setImageFormat($p_sExtension); $oImage->setImageCompression(Imagick::COMPRESSION_JPEG); $a = $oImage->getImageCompressionQuality() * 0.75; if ($a == 0) { $a = 75; } $oImage->setImageCompressionQuality($a); $oImage->stripImage(); $blImage = $oImage->getImageBlob(); $oImage->clear(); $oImage->destroy(); return $blImage; }
/** * @desc Create a thumbnail of the picture and save it * @param $size The size requested */ private function createThumbnail($width, $height = false, $format = 'jpeg') { if (!in_array($format, array_keys($this->_formats))) { $format = 'jpeg'; } if (!$height) { $height = $width; } $path = $this->_path . md5($this->_key) . '_' . $width . $this->_formats[$format]; $im = new Imagick(); try { $im->readImageBlob($this->_bin); $im->setImageFormat($format); if ($format == 'jpeg') { $im->setImageCompression(Imagick::COMPRESSION_JPEG); $im->setImageAlphaChannel(11); // Put 11 as a value for now, see http://php.net/manual/en/imagick.flattenimages.php#116956 //$im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); $im->setImageBackgroundColor('#ffffff'); $im = $im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); } //$crop = new CropEntropy; //$crop->setImage($im); $geo = $im->getImageGeometry(); $im->cropThumbnailImage($width, $height); if ($width > $geo['width']) { $factor = floor($width / $geo['width']); $im->blurImage($factor, 10); } //$im = $crop->resizeAndCrop($width, $height); $im->setImageCompressionQuality(85); $im->setInterlaceScheme(Imagick::INTERLACE_PLANE); $im->writeImage($path); $im->clear(); } catch (ImagickException $e) { error_log($e->getMessage()); } }
public function createMediaFromJSON($glob) { $path = $glob->path; $filename = $glob->filename; $data = $glob->data; $resizeTo = isset($glob->resizeTo) ? $glob->resizeTo : null; $gameMediaDirectory = Media::getMediaDirectory($path)->data; $md5 = md5((string) microtime() . $filename); $ext = strtolower(substr($filename, -3)); $newMediaFileName = 'aris' . $md5 . '.' . $ext; $resizedMediaFileName = 'aris' . $md5 . '_128.' . $ext; if ($ext != "jpg" && $ext != "png" && $ext != "gif" && $ext != "mp4" && $ext != "mov" && $ext != "m4v" && $ext != "3gp" && $ext != "caf" && $ext != "mp3" && $ext != "aac" && $ext != "m4a" && $ext != "zip") { return new returnData(1, NULL, "Invalid filetype:{$ext}"); } $fullFilePath = $gameMediaDirectory . "/" . $newMediaFileName; if (isset($resizeTo) && ($ext == "jpg" || $ext == "png" || $ext == "gif")) { $bigFilePath = $gameMediaDirectory . "/big_" . $newMediaFileName; $fp = fopen($bigFilePath, 'w'); if (!$fp) { return new returnData(1, NULL, "Couldn't open file:{$bigFilePath}"); } fwrite($fp, base64_decode($data)); fclose($fp); $image = new Imagick($bigFilePath); // Reorient based on EXIF tag switch ($image->getImageOrientation()) { case Imagick::ORIENTATION_UNDEFINED: // We assume normal orientation break; case Imagick::ORIENTATION_TOPLEFT: // All good break; case Imagick::ORIENTATION_TOPRIGHT: $image->flopImage(); break; case Imagick::ORIENTATION_BOTTOMRIGHT: $image->rotateImage('#000', 180); break; case Imagick::ORIENTATION_BOTTOMLEFT: $image->rotateImage('#000', 180); $image->flopImage(); break; case Imagick::ORIENTATION_LEFTTOP: $image->rotateImage('#000', 90); $image->flopImage(); break; case Imagick::ORIENTATION_RIGHTTOP: $image->rotateImage('#000', 90); break; case Imagick::ORIENTATION_RIGHTBOTTOM: $image->rotateImage('#000', -90); $image->flopImage(); break; case Imagick::ORIENTATION_LEFTBOTTOM: $image->rotateImage('#000', -90); break; } $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT); // Resize image proportionally so min(width, height) == $resizeTo if ($image->getImageWidth() < $image->getImageHeight()) { $image->resizeImage($resizeTo, 0, Imagick::FILTER_LANCZOS, 1); } else { $image->resizeImage(0, $resizeTo, Imagick::FILTER_LANCZOS, 1); } $image->setImageCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(40); $image->writeImage($fullFilePath); unlink($bigFilePath); } else { $fp = fopen($fullFilePath, 'w'); if (!$fp) { return new returnData(1, NULL, "Couldn't open file:{$fullFilePath}"); } fwrite($fp, base64_decode($data)); fclose($fp); } if ($ext == "jpg" || $ext == "png" || $ext == "gif") { $img = WideImage::load($fullFilePath); $img = $img->resize(128, 128, 'outside'); $img = $img->crop('center', 'center', 128, 128); $img->saveToFile($gameMediaDirectory . "/" . $resizedMediaFileName); } else { if ($ext == "mp4") { /* $ffmpeg = '../../libraries/ffmpeg'; $videoFilePath = $gameMediaDirectory."/".$newMediaFileName; $tempImageFilePath = $gameMediaDirectory."/temp_".$resizedMediaFileName; $imageFilePath = $gameMediaDirectory."/".$resizedMediaFileName; $cmd = "$ffmpeg -i $videoFilePath 2>&1"; $thumbTime = 1; if(preg_match('/Duration: ((\d+):(\d+):(\d+))/s', shell_exec($cmd), $videoLength)) $thumbTime = (($videoLength[2] * 3600) + ($videoLength[3] * 60) + $videoLength[4])/2; $cmd = "$ffmpeg -i $videoFilePath -deinterlace -an -ss $thumbTime -t 00:00:01 -r 1 -y -vcodec mjpeg -f mjpeg $tempImageFilePath 2>&1"; shell_exec($cmd); $img = WideImage::load($tempImageFilePath); $img = $img->resize(128, 128, 'outside'); $img = $img->crop('center','center',128,128); $img->saveToFile($imageFilePath); */ } } $m = Media::createMedia($path, "UploadedMedia", $newMediaFileName, 0); return new returnData(0, $m->data); }
/** * @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; } }
/** * Creates a thumbnail from a source file and returns it with some info as a string. * If the source is not processable or not accessible the function returns false * * @param string $sourceFile Path to the source file * @param string $targetFile Path to the thumbnail file * @return bool * @throws CreateThumbnailException */ public function create($sourceFile, $targetFile) { // File not accessible if (!file_exists($sourceFile) || !is_readable($sourceFile)) { throw new CreateThumbnailException(sprintf('File %s not found or not readable', $sourceFile)); } $generated = false; // File supposedly too large $sourceFileSize = filesize($sourceFile); if ($sourceFileSize > $this->sourceMaxBytes) { throw new CreateThumbnailException(sprintf('File too large: %d bytes, allowed: %d bytes', $sourceFileSize, $this->sourceMaxBytes)); } // Try ImageMagick on command line try { exec(sprintf('convert %s -resize %dx%d -background white -alpha remove -quality %d %s:%s', $sourceFile, $this->targetWidth, $this->targetHeight, $this->jpegCompressionQuality, \strtolower($this->targetType), $targetFile)); if (file_exists($targetFile) && is_readable($targetFile) && filesize($targetFile)) { $generated = true; } } catch (\Exception $e) { // regular exceptions are caught to try the next mechanism } // Try Imagick's PHP API // This is really much of a shot in the dark, no checking, nothing! if (!$generated && class_exists('Imagick')) { // path to the sRGB ICC profile $srgbPath = __DIR__ . '/srgb_v4_icc_preference.icc'; // load the original image $image = new \Imagick($sourceFile); // get the original dimensions $owidth = $image->getImageWidth(); $oheight = $image->getImageHeight(); if ($owidth * $oheight < $this->sourceMaxPixels) { // set colour profile // this step is necessary even though the profiles are stripped out in the next step to reduce file size $srgb = file_get_contents($srgbPath); $image->profileImage('icc', $srgb); // strip colour profiles $image->stripImage(); // set colorspace $image->setImageColorspace(\Imagick::COLORSPACE_SRGB); // determine which dimension to fit to $fitWidth = $this->targetWidth / $owidth < $this->targetHeight / $oheight; // create thumbnail $image->thumbnailImage($fitWidth ? $this->targetWidth : 0, $fitWidth ? 0 : $this->targetHeight); $image->setImageFormat(strtolower($this->targetType)); if ($this->targetType == 'JPEG') { $image->setImageCompression(\Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality($this->jpegCompressionQuality); } $image->writeImage($targetFile); $image->clear(); $image->destroy(); if (file_exists($targetFile) && is_readable($targetFile) && filesize($targetFile)) { $generated = true; } } else { throw new CreateThumbnailException(sprintf('File pixel count is too large: %d x %d', $owidth, $oheight)); } } // Try GD if (!$generated && function_exists('imagecreatetruecolor')) { $ii = @getimagesize($sourceFile); // Only try creating the thumbnail with the correct GD support. // GIF got dropped a while ago, then reappeared again; JPEG or PNG might not be compiled in if ($ii[2] == 1 && !function_exists('imagecreatefromgif')) { $ii[2] = 0; } if ($ii[2] == 2 && !function_exists('imagecreatefromjpeg')) { $ii[2] = 0; } if ($ii[2] == 3 && !function_exists('imagecreatefrompng')) { $ii[2] = 0; } if ($ii[2] == 15 && !function_exists('imagecreatefromwbmp')) { $ii[2] = 0; } // a supported source image file type, pixel dimensions small enough and source file not too big if (!empty($ii[2]) && $ii[0] * $ii[1] < $this->sourceMaxPixels) { $ti = $ii; if ($ti[0] > $this->targetWidth || $ti[1] > $this->targetHeight) { $wf = $ti[0] / $this->targetWidth; // Calculate width factor $hf = $ti[1] / $this->targetHeight; // Calculate height factor if ($wf >= $hf && $wf > 1) { $ti[0] /= $wf; $ti[1] /= $wf; } elseif ($hf > 1) { $ti[0] /= $hf; $ti[1] /= $hf; } $ti[0] = round($ti[0], 0); $ti[1] = round($ti[1], 0); } if ($ii[2] == 1) { $si = imagecreatefromgif($sourceFile); } elseif ($ii[2] == 2) { $si = imagecreatefromjpeg($sourceFile); } elseif ($ii[2] == 3) { $si = imagecreatefrompng($sourceFile); imagesavealpha($si, true); } elseif ($ii[2] == 15) { $si = imagecreatefromwbmp($sourceFile); } if (!empty($si)) { $tn = imagecreatetruecolor($ti[0], $ti[1]); // The following four lines prevent transparent source images from being converted with a black background imagealphablending($tn, false); imagesavealpha($tn, true); $transparent = imagecolorallocatealpha($tn, 255, 255, 255, 0); imagefilledrectangle($tn, 0, 0, $ti[0], $ti[1], $transparent); // imagecopyresized($tn, $si, 0, 0, 0, 0, $ti[0], $ti[1], $ii[0], $ii[1]); // Get the thumbnail ob_start(); if (imagetypes() & IMG_JPG && $this->targetType == 'JPEG') { imagejpeg($tn, null, $this->jpegCompressionQuality); } elseif (imagetypes() & IMG_PNG && $this->targetType == 'PNG') { imagepng($tn, null); } elseif (imagetypes() & IMG_GIF && $this->targetType == 'GIF') { imagegif($tn, null); } else { throw new CreateThumbnailException(sprintf('Your desired output type %s is not available', $this->targetType)); } file_put_contents($targetFile, ob_get_clean()); imagedestroy($tn); } } else { throw new CreateThumbnailException(sprintf('File pixel count is too large: %d x %d', $ii[0], $ii[1])); } } elseif (!$generated) { throw new CreateThumbnailException('GD library not installed, ImageMagick neither'); } return true; }
/** * 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(); }