function compressAndResizeImage($source, $maxWidth=1080, $quality=39) {
$path = pathinfo($source);
//创建文件夹
$smallPath = $path['dirname'].'/small';
if(!is_dir($smallPath)){
mkdir($path['dirname'].'/small',0777,true);
}
// 压缩后保存的路径
$destination = $smallPath.'/'.$path['filename'].'.jpg';
if(file_exists($destination)){
return $destination;
}
// 获取原始图片的信息
list($origWidth, $origHeight, $type) = getimagesize($source);
// 创建原始图片资源
if ($type == IMAGETYPE_JPEG) {
$sourceImage = imagecreatefromjpeg($source);
} elseif ($type == IMAGETYPE_PNG) {
$sourceImage = imagecreatefrompng($source);
} elseif ($type == IMAGETYPE_GIF) {
$sourceImage = imagecreatefromgif($source);
}else {
$sourceImage = imagecreatefromstring($source);
}
if ($origWidth > $maxWidth) {
// 计算缩放比例
$ratio = $maxWidth / $origWidth;
$newWidth = $maxWidth;
$newHeight = $origHeight * $ratio;
// 创建缩放后的图片资源
$newImage = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight);
// 保存缩放后的图片
imagejpeg($newImage, $destination, $quality);
imagedestroy($newImage);
} else{
imagejpeg( $sourceImage, $destination, $quality);
// 释放内存
imagedestroy($sourceImage);
}
return $destination;
}
相关文章