php等比缩放图片并计算其margin,适用于处理宽高比例不一致但要求显示一致的图片场合。
/*
* 等比缩放图片并计算其margin
* @param $picpath 图片路径
* @param $pwidth 要显示的宽度
* @param $pheight 要显示的高度
* @return array 宽高,margin的top和left(bottom=top,right=left)
*/
function resizeImageWHM($picpath,$pwidth,$pheight){
$imginfo=getimagesize($picpath);
$owidth=$imginfo[0];
$oheight=$imginfo[1];
$ra=number_format(($owidth/$pwidth),3);//宽比
$ra2=number_format(($oheight/$pheight),3);//高比
if($owidth>$pwidth && $oheight>$pheight){
if($ra>=$ra2){
$width=round($owidth/$ra);;
$height=round($oheight/$ra);
}else{
$width=round($owidth/$ra2);
$height=round($oheight/$ra2);
}
}else{
$width=$owidth;
$height=$oheight;
}
$margin_top=0;
if($height<$pheight){
$margin_top=round(($pheight-$height)/2);
}
$margin_left=0;
if($width<$pwidth){
$margin_left=round(($pwidth-$width)/2);
}
$newsize['width']=$width;
$newsize['height']=$height;
$newsize['margin_top']=$margin_top;
$newsize['margin_left']=$margin_left;
return $newsize;
}