查找php缩放处理函数
函数resizeImage($im,$maxwidth,$maxheight,$name,$filetype)
{
$ pic _ width = imagesx($ im);
$ pic _ height = imagesy($ im);
if(($ maxwidth & amp;& amp$ pic _ width & gt$ maxwidth)($ max height & amp;& amp$ pic _ height & gt$maxheight))
{
if($ maxwidth & amp;& amp$ pic _ width & gt$maxwidth)
{
$ width ratio = $ maxwidth/$ pic _ width;
$ resizewidth _ tag = true
}
if($max height & amp;& amp$ pic _ height & gt$maxheight)
{
$ height ratio = $ max height/$ pic _ height;
$ resizeheight _ tag = true
}
if($ resize width _ tag & amp;& amp$resizeheight_tag)
{
if($ width ratio & lt;$heightratio)
$ ratio = $ widthratio
其他
$ ratio = $ heightratio
}
if($ resize width _ tag & amp;& amp!$resizeheight_tag)
$ ratio = $ widthratio
if($ resize height _ tag & amp;& amp!$resizewidth_tag)
$ ratio = $ heightratio
$ newwidth = $ pic _ width * $ ratio
$ newheight = $ pic _ height * $ ratio
if(function _ exists(" imagecopyresampled "))
{
$ newim = imagecreatetruecolor($ new width,$ new height);
imagecopyresampled($newim,$im,0,0,0,$newwidth,$newheight,$pic_width,$ pic _ height);
}
其他
{
$newim = imagecreate($newwidth,$ new height);
imagecopyrestized($ newim,$im,0,0,0,$newwidth,$newheight,$pic_width,$ pic _ height);
}
$name = $name。$ filetype
imagejpeg($newim,$ name);
image destroy($ newim);
}
其他
{
$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 & gt$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格式,但在1.6.2版本之后不支持GIF格式,因为GIF格式中LZW算法的使用涉及专利权。如果是WINDOWS环境,输入PHP就可以了。INI文件找到extension=php_gd2.dll,去掉#并重启APACHE。如果是Linux环境,想支持GIF、PNG、JPEG,需要下载安装libpng、zlib、freetype字体。
好了,PHP图像压缩功能完成了,最后总结一下整个处理思路:
通过计算实际图片的长宽与生成图片的指定长宽之间的缩放比例,根据实际需求计算出最终生成图片的大小(图片是按宽度缩放还是按高度缩放),然后利用PHP图片处理函数对图片进行处理,最后输出图片。
以上是关于PHP图片处理中如何压缩图片并保持不失真的函数描述。