您的位置:首页 > 编程语言 > PHP开发

PHP等比缩放并补白

2016-08-10 22:21 183 查看
/**
* 图片等比缩放并补白
* @param string $filename   	图片路径
* @param number $width		缩放宽度
* @param number $height		缩放高度
* @return $newname             新文件名
*/
function zoom($filename,$width=400,$height=400){
//获取图片信息
$info = getimagesize($filename);

//判断是不是图片
if(!$info) exit('请处理图片');

$arr = explode('/',$info['mime']);
$ext = $arr[1];

//拼接相关函数  打开   保存
$create = 'imagecreatefrom'.$ext;
$save = 'image'.$ext;

//获取图片原来信息
list($t_w,$t_h) = $info;

//要计算图片最终的宽高
//假设用图片的宽度来计算出图片的高度
$des_w = $width;
$des_h = $des_w * ($t_h/$t_w);

if($des_h > $height){
$des_h = $height;
$des_w = $des_h * ($t_w/$t_h);
}else{
$des_w = $width;
$des_h = $des_w * ($t_h/$t_w);
}

//创建画布
$huabu = imagecreatetruecolor($width,$height);
$white = imagecolorallocate($huabu,255,255,255);
imagefill($huabu,0,0,$white);
$tupian = $create($filename);

//画布起点
//横坐标
$hua_x = ($width-$des_w)/2;
$hua_y = ($height-$des_h)/2;

imagecopyresampled($huabu,$tupian,$hua_x,$hua_y,0,0,$des_w,$des_h,$t_w,$t_h);
if($ext == 'jpeg') $ext = 'jpg';
$newname = uniqid().'.'.$ext;
$savepath = rtrim(dirname($filename),'/').'/'.$newname;
$save($huabu,$savepath);

imagedestroy($huabu);
imagedestroy($tupian);

return $newname;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: