php图片等比例缩放.doc
文本预览下载声明
在PHP网站开发过程中,如果你建立的网站涉及大量的图片处理,必然涉及到图片上传,缩放,而如何保持图片不失真,是很多初级PHP网站开发者比较头疼的一件事,今天David就和大家分享一下如何进行图片缩放。使用之前你需要下载安装GD库,以支持PHP图片处理。下面我们结合代码讲解具体的PHP图片缩放处理的思路。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 function resizeImage($im,$maxwidth,$maxheight,$name,$filetype){$pic_width = imagesx($im);$pic_height = imagesy($im);if(($maxwidth $pic_width $maxwidth) || ($maxheight $pic_height $maxheight)){if($maxwidth $pic_width$maxwidth){$widthratio = $maxwidth/$pic_width;$resizewidth_tag = true;}if($maxheight $pic_height$maxheight){$heightratio = $maxheight/$pic_height;$resizeheight_tag = true;}if($resizewidth_tag $resizeheight_tag){if($widthratio$heightratio)$ratio = $widthratio;else$ratio = $heightratio;}if($resizewidth_tag !$resizeheight_tag)$ratio = $widthratio;if($resizeheight_tag !$resizewidth_tag)$ratio = $heightratio;$newwidth = $pic_width * $ratio;$newheight = $pic_height * $ratio;if(function_exists(imagecopyresampled)){$newim = imagecreatetruecolor($newwidth,$newheight);imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);}else{$newim = imagecreate($newwidth,$newheight);imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);}$name = $name.$filetype;imagejpeg($newim,$name);imagedestroy($newim);}else{$name = $name.$filetype;imagejpeg($im,$name);}}
参数说明:
$im 图片对象,应用函数之前,你需要用imagecreatefromjpeg()读取图片对象,如果PHP环境支持PNG,GIF,也可使用imagecreatefromgif(),imagecreatefrompng();
$maxwidth 定义生成图片的最大宽度(单位:像素)
$maxheight 生成图片的最大高度(单位:像素)
$name 生成的图片名
$filetype 最终生成的图片类型(.jpg/.png/.gif)
代码注释:
第3~4行:读取需要缩放的图片实际宽高
第8~26行:通过计算实际图片宽高与需要生成图片的宽高的压缩比例最终得出进行图片缩放是根据宽度还是高度进行缩放,当前程序是根据宽度进行图片缩放。如果你想根据高度进行图片缩放,你可以将第22行的语句改成$widthratio$heightratio
第28~31行:如果实际图片的长度或者宽度小于规定生成图片的长度或者宽度,则要么根据长度进行图片缩放,要么根据宽度进行图片缩放。
第33~34行:计算最终缩放生成的图片长宽。
第36~45行:根据计算出的最终生成图片的长宽改变图片大小,有两种改变图片大小的方
显示全部