应用场景:
app 小程序 以及管理后台上传的图片很大,占用空间且无用,则考虑进行图片压缩。
php代码如下:
/**
* 上传后重新压缩图片
* @param $sourcePath 原图
* @param $targetPath 保存路径
* @param $quality 图片质量
*/
function compressImage($sourcePath, $targetPath, $quality) {
$info = getimagesize($sourcePath);
$mime = $info['mime'];
$width = $info[0];
$height = $info[1];
//压缩后的图片宽
$newWidth = $width;
//压缩后的图片高
$newHeight = $height;
// 压缩到750宽
if($width >= 750){
$per = 750 / $width;//计算比例
$newWidth = $width * $per;
$newHeight = $height * $per;
}
$image_wp = imagecreatetruecolor($newWidth, $newHeight);
switch($mime) {
case 'image/jpeg':
$image = imagecreatefromjpeg($sourcePath);
break;
case 'image/png':
$image = imagecreatefrompng($sourcePath);
break;
case 'image/gif':
$image = imagecreatefromgif($sourcePath);
break;
default:
return false;
}
imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
imagejpeg($image_wp, $targetPath, $quality);
imagedestroy($image);
imagedestroy($image_wp);
return true;
}