简述:
使用php的GD库可以将图片按固定宽高或者等比例压缩,主要利用的函数是:
imagecopyresampled:将一张图片中的一块区域复制到另一张图片上
等比例压缩
/**
* [compressImg description]
* @param string $src 源图片
* @param integer $percent 压缩比例
* @return [type] [description]
*/
public function compressImg($src = '', $percent = 1)
{
list($width, $height, $type, $attr) = getimagesize($src);
$type = image_type_to_extension($type, false);
$fun = "imagecreatefrom" . $type;
$image = $fun($src);
$new_width = $width * $percent;
$new_height = $height * $percent;
$thump = imagecreatetruecolor($new_width, $new_height);
//将原图复制到另一张图片上,并且按照一定比例压缩
imagecopyresampled($thump, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($image);
$image = $thump;
// 1、浏览器直接输出
header('Content-Type: image/' . $type);
$funcs = "image" . $type;
$funcs($thump);
// 2、保存到对应路径
$path = 'save.'.$type;
$funcs = "image" . $type;
$funcs($thump, $path);
}
按固定宽高压缩
/**
* [compressImgWH description]
* @param string $src 源图片
* @param string $new_width 压缩后宽度
* @param string $new_height 压缩后高度
* @return [type] [description]
*/
public function compressImgWH($src = '', $new_width='', $new_height=''){
list($width, $height, $type, $attr) = getimagesize($src);
$type = image_type_to_extension($type, false);
$fun = "imagecreatefrom" . $type;
$image = $fun($src);
$thump = imagecreatetruecolor($new_width, $new_height);
// 处理透明背景图片变成黑色的问题
if(strtolower($type)=='png'){
imageantialias($thump, true);
$color = imagecolorallocate($thump, 255, 255, 255);
imagecolortransparent($thump, $color);
imagefill($thump, 0, 0, $color);
}
//将原图复制到其他图片上,并且按照一定宽高压缩
imagecopyresampled($thump, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagedestroy($image);
// 1、浏览器直接输出
header('Content-Type: image/' . $type);
$funcs = "image" . $type;
$funcs($thump);
// 2、保存到对应路径
$path = 'save.'.$type;
$funcs = "image" . $type;
$funcs($thump, $path);
}
功能演示: