/**
* 图片压缩处理
* @param string $oldImg 源图片路径
* @param int $width 自定义图片宽度
* @param int $height 自定义图片高度
* @return string 压缩后的图片路径
*/
function getThumb($oldImg,$width = 0,$height = 0){
//判断该图片是否存在
if(!file_exists($oldImg)){
return false;
}
//判断图片格式(图片文件后缀)
$pathArr = pathinfo($oldImg);
$extend = $pathArr['extension'];
if(!in_array($extend,['jpg','png','jpeg'])){
return false;
}
//未设置宽高 则以原尺寸压缩
$oldImgInfo = getimagesize($oldImg);
if(!$width){
$width = $oldImgInfo[0];
}
if(!$height){
$height = $oldImgInfo[1];
}
//压缩图片文件名称
$newImg = str_replace('.'.$extend, '_thumb_'.$width.'_'.$height.'.'.$extend, $oldImg);
//判断是否已压缩图片,若是则返回压缩图片路径
if(file_exists($newImg)){
return $newImg;
}
//生成压缩图片,并存储到原图同路径下
resizeImage($oldImg, $newImg, $width, $height);
if(!file_exists($newImg)){
return $oldImg;
}
return $newImg;
}
/**
* 生成图片
* @param string $oldImgPath 源图片路径
* @param string $newImgPath 目标图片路径
* @param int $width 生成图片宽
* @param int $height 生成图片高
*/
function resizeImage($oldImgPath, $newImgPath, $width, $height) {
$img = getimagesize($oldImgPath);
switch ($img[2]) {
case 1:
$resource = @imagecreatefromgif($oldImgPath);
break;
case 2:
$resource = @imagecreatefromjpeg($oldImgPath);
break;
case 3:
$resource = @imagecreatefrompng($oldImgPath);
break;
default:
$resource = @imagecreatefrompng($oldImgPath);
break;
}
//原图的宽
$pic_width = imagesx($resource);
//原图的高
$pic_height = imagesy($resource);
//判断是否压缩
$resize_width_tag = $resize_height_tag = false;
//默认压缩率1,即等尺寸压缩
$width_ratio = $height_ratio = 1;
if(($width && $pic_width > $width) || ($height && $pic_height > $height)){
//宽度是否压缩
if($width && $pic_width > $width){
$width_ratio = $width / $pic_width;
$resize_width_tag = true;
}
//高度是否压缩
if($height && $pic_height > $height){
$height_ratio = $height / $pic_height;
$resize_height_tag = true;
}
//选择压缩率
if($resize_width_tag && $resize_height_tag){
if ($width_ratio < $height_ratio){
$ratio = $width_ratio;
} else{
$ratio = $height_ratio;
}
}elseif ($resize_width_tag && !$resize_height_tag){
$ratio = $width_ratio;
}elseif ($resize_height_tag && !$resize_width_tag){
$ratio = $height_ratio;
}else{
$ratio = 1;
}
$new_width = $pic_width * $ratio;
$new_height = $pic_height * $ratio;
if(function_exists("imagecopyresampled")){
$newim = imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($newim, $resource, 0, 0, 0, 0, $new_width, $new_height, $pic_width, $pic_height);
}else{
$newim = imagecreate($new_width, $new_height);
imagecopyresized($newim, $resource, 0, 0, 0, 0, $new_width, $new_height, $pic_width, $pic_height);
}
imagejpeg($newim, $newImgPath);
imagedestroy($newim);
} else {
imagejpeg($resource, $newImgPath);
}
}
|