类别:PHP问题 / 日期:2019-11-26 / 浏览:163 / 评论:0

php不变形缩放图片:
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行:依据盘算出的终究生成图片的长宽转变图片大小,有两种转变图片大小的要领:ImageCopyResized()函数在所有GD版本中有用,但其缩放图象的算法比较粗拙。ImageCopyResamples(),其像素插值算法获得的图象边沿比较腻滑,但该函数的速率比ImageCopyResized()慢。
第47~49行:终究生成经由处置惩罚后的图片,假如你须要生成GIF或PNG,你须要将imagejpeg()函数改成imagegif()或imagepng()
第51~56行:假如现实图片的长宽小于划定生成的图片长宽,则坚持图片原样,同理,假如你须要生成GIF或PNG,你须要将imagejpeg()函数改成imagegif()或imagepng()。
迥殊申明:
GD库1.6.2版之前支撑GIF花样,但因GIF花样运用LZW演算法牵扯专利权,因此在GD1.6.2版以后不支撑GIF的花样。假如你是WINDOWS的环境,你只需进入PHP.INI文件找到extension=php_gd2.dll,将#去除,重启APACHE即可,假如你是Linux环境,又想支撑GIF,PNG,JPEG,你须要去下载libpng,zlib,以及freetype字体并装置。
引荐:php服务器
以上就是php不变形缩放图片的细致内容,更多请关注ki4网别的相干文章!