php按照固定宽/高对图片进行压缩处理

按照固定宽,高对图片进行压缩,根据实际比例,按照宽度优先或者高度优先,对图片进行压缩,不够的尺寸进行留白,在使用过程中,php的这个imagecreatetruecolor()函数可能会报错

Call to undefined function imagecreatetruecolor() in

发现是php5.4.3默认没有开启该扩展。

要在php.ini中,去掉 extension=php_gd2.dll 前分号,此扩展用于图片类处理,因此要开启,使用方法如下:

header("Content-Type: text/html;charset=utf-8");

$result = resize('0.jpg');

echo $result;exit;


/**
 * 图片压缩,比例不够部分留白
 * @param  [type]  $src          图片地址
 * @param  integer $width_value  压缩后的图片宽度
 * @param  integer $height_value 压缩后的图片高度
 * @return str 生成的图片地址
 */
function resize($src, $width_value=535, $height_value=400) {
    $temp = pathinfo($src);
    $filename = time().'.jpg';
    $dir = $temp["dirname"];    //文件所在的文件夹     
    $savepath = "{$dir} / $filename"; //缩略图保存路径		 
    //获取图片的基本信息     
    $info = getimagesize($src);
    $width = $info[0];      //获取图片宽度     
    $height = $info[1];     //获取图片高度 
  	if(($width/$height) >= ($width_value/$height_value)){ //宽度优先
		$w_mid = $width_value;						  //压缩后图片的宽度
		$h_mid = intval($width_value * $height/$width);//等比缩放图片高度		
		$mid_x = 0;
		$mid_y = intval(($height_value-$h_mid)/2);
	}else{											//高度优先
		$w_mid = intval($height_value * $width/$height);							//压缩后图片的宽度
		$h_mid = $height_value;//等比缩放图片高度				
		$mid_x = intval(($width_value-$w_mid)/2);
		$mid_y = 0;
	}   

	$temp_img = imagecreatetruecolor($width_value , $height_value);		//创建画布   
	$white = imagecolorallocate($temp_img, 255, 255, 255);
	imagefill($temp_img, 0, 0, $white);		
	$im = create($src);    
	imagecopyresampled($temp_img, $im, $mid_x, $mid_y, 0, 0, $w_mid, $h_mid, $width, $height);     
	imagejpeg($temp_img,$savepath, 100);     
	imagedestroy($im);  

    return $savepath;
}

/**
 * 创建图片,返回资源类型 
 * @param  string $src 图片路径   
 * @return resource $im 返回资源类型   
 */
function create($src) {
    $info = getimagesize($src);
    switch ($info[2]) {
        case 1:
            $im = imagecreatefromgif($src);
            break;
        case 2:
            $im = imagecreatefromjpeg($src);
            break;
        case 3:
            $im = imagecreatefrompng($src);
            break;
    }
    return $im;
}

猜你喜欢

转载自blog.csdn.net/a_jie_2016_05/article/details/82774612
今日推荐