zoukankan      html  css  js  c++  java
  • 使用PHP的GD2裁剪 + 缩放图片

    	/**
    	 * 裁剪 + 缩放图片
    	 * @param array $params 包含x,y,width,height,path
    	 * @return string
    	 */
    	public function tailer_image($params){
    		//$target_width,$target_height是缩放图片的大小
    		$target_width = 256;
    		$target_height = 256;
    		$source_x = intval($params['x']);
    		$source_y = intval($params['y']);
    		$cropped_width = intval($params['width']);
    		$cropped_height = intval($params['height']);
    		$source_path = trim($params['path']);
    		$path = 'files/uploads/images/';
    		list($source_width,$source_height) = getimagesize($source_path);
    		//获取图片的扩展名
    		$extend_name = ltrim(strrchr(strtolower($source_path),'.'),'.');
    		if(!in_array($extend_name,array('jpg','jpeg','png'))){
    			return array(
    						array('message'=>"图片扩展名不正确,只允许'jpg','jpeg','png'"),
    						400
    					);
    		}
    
    		switch ($extend_name) {
    			case 'jpg':
    				$source_image = imagecreatefromjpeg($source_path);
    				break;
    			case 'jpeg':
    				$source_image = imagecreatefromjpeg($source_path);
    				break;
    			case 'png':
    				$source_image = imagecreatefrompng($source_path);
    				break;
    		}
    		
    		$target_image  = imagecreatetruecolor($target_width, $target_height);
    		$cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);
    		// 裁剪
    		imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
    		// 缩放
    		imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);
    		$filename = md5(microtime()).'.'.$extend_name;
    		$dst_url = $path.$filename;
    		//输出图像到$dst_url文件
    		imagejpeg($target_image, $dst_url);
    		return $dst_url;
    	}
    
  • 相关阅读:
    木棍加工 [搜索]
    (转)CSP前必须记住的30句话
    [NOI2015] 程序自动分析
    JOI 2019 Final 硬币收藏
    可达性统计
    CSP-S初赛考纲内容大全
    AT2021 キャンディーとN人の子供 / Children and Candies
    AT2067 たくさんの数式 / Many Formulas
    NOIP2018提高组初赛某题
    String转Map集合
  • 原文地址:https://www.cnblogs.com/zhangxiaoliu/p/6214008.html
Copyright © 2011-2022 走看看