/*@todo 原比例生成缩略图
*@param $path string 图片路径
*@param $savePath string 缩略图将要保存的路径
*@param $maxwidth int 最大宽度
*@param $maxheight int 最大高度
*/
function thumbImage($path,$savePath,$maxwidth=200,$maxheight=200){
$return['error']=0;
$tips=array(0=>'生成缩略图成功',1=>'原图片不存在,或存放缩略图路径不存在',2=>'图片格式不对或不支持!',3=>'生成失败');
if(file_exists($path) && is_dir($savePath)){
$imgInfo=getimagesize($path);//获取文件的宽高
$pathinfo=pathinfo($path); //获取文件的名称和后缀
$newFileName=$savePath.$pathinfo['filename'].'_thumb'.'.'.$pathinfo['extension'];
$newwidth=$maxwidth;
$newheight=$maxwidth*($imgInfo[1]/($imgInfo[0]));
if($newheight>$maxheight){
$newheight= $maxheight;
$newwidth = $maxheight*($imgInfo[0]/($imgInfo[1]));
}
switch ($imgInfo['mime']) {
case 'image/jpeg':
case 'image/pjpeg':
$image=imagecreatefromjpeg($path);//把原图转化为图片资源
$fun='imagejpeg';
$thumb = imagecreatetruecolor($newwidth, $newheight);//创建一张黑色的新图
imagecopyresampled($thumb,$image,0,0,0,0,$newwidth,$newheight,$imgInfo[0],$imgInfo[1]);
break;
case 'image/png':
case 'image/x-png':
$image=imagecreatefrompng($path);
$fun='imagepng';
imagesavealpha($image,true);//原图不要丢失透明色
$thumb = imagecreatetruecolor($newwidth, $newheight);//创建一张新图
imagealphablending($thumb,false);//不允许混色模式,图片透明部分才能被保存下来
imagesavealpha($thumb,true);//缩略图不丢失透明色
imagecopyresampled($thumb,$image,0,0,0,0,$newwidth,$newheight,$imgInfo[0],$imgInfo[1]);
break;
case 'image/gif':
//=======================================================//
//注:GD库对GIF处理只能取得第一帧,所以生成的缩略图为静态。//
//如需生成动态缩略图,需要加载第三方扩展 如ImageMagick //
//=======================================================//
$image=imagecreatefromgif($path);
$fun='imagegif';
$thumb = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($thumb,$image,0,0,0,0,$newwidth,$newheight,$imgInfo[0],$imgInfo[1]);
break;
default:
$return['error']=2;
$return['tip']=$tips[2];
return $return;
}
//$fun($thumb,$newFileName)相当于
//imagejpeg($thumb,$newFileName)/imagepng($thumb,$newFileName)/imagegif($thumb,$newFileName);
$res=$fun($thumb,$newFileName); //输出图片
imagedestroy($thumb); //销毁缓存的缩略图
if(!$res){
$return['error']=3;
$return['tip']=$tips[3];
}
$return['tip']=$tips[0];
}else{
$return['error']=1;
$return['tip']=$tips[1];
}
return $return;
}
注:为了体现不同图片格式的区别代码冗余度比较高,实际使用时可以适当修改