有时上传图片时因为图片太大了,不仅占用空间,消耗流量,而且影响浏(图片的尺寸大小不一)。下面分享一种等比例不失真缩放图片的方法,这样,不管上传的图片尺有多大,都会自动压缩到我们设置尺寸值的范围之内。经过测试,证明实用。
02 |
function resizeImage($im,$maxwidth,$maxheight,$name,$filetype) |
04 |
$pic_width = imagesx($im); |
05 |
$pic_height = imagesy($im); |
07 |
if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) |
09 |
if($maxwidth && $pic_width>$maxwidth) |
11 |
$widthratio = $maxwidth/$pic_width; |
12 |
$resizewidth_tag = true; |
15 |
if($maxheight && $pic_height>$maxheight) |
17 |
$heightratio = $maxheight/$pic_height; |
18 |
$resizeheight_tag = true; |
21 |
if($resizewidth_tag && $resizeheight_tag) |
23 |
if($widthratio<$heightratio) |
26 |
$ratio = $heightratio; |
29 |
if($resizewidth_tag && !$resizeheight_tag) |
31 |
if($resizeheight_tag && !$resizewidth_tag) |
32 |
$ratio = $heightratio; |
34 |
$newwidth = $pic_width * $ratio; |
35 |
$newheight = $pic_height * $ratio; |
37 |
if(function_exists("imagecopyresampled")) |
39 |
$newim = imagecreatetruecolor($newwidth,$newheight); |
40 |
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); |
44 |
$newim = imagecreate($newwidth,$newheight); |
45 |
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); |
48 |
$name = $name.$filetype; |
49 |
imagejpeg($newim,$name); |
54 |
$name = $name.$filetype; |
59 |
$im=imagecreatefromjpeg("./20140416103023202.jpg"); |
64 |
resizeImage($im,$maxwidth,$maxheight,$name,$filetype); |
处理前图片大小:1187*846
图片处理后大小:561*400
处理后的图片名称:123.jpg
写 在最后:因为客户要求使用php实现等比例不失真缩放上传图片,本来要自己写的,但百度一下发现了这个函数,于是乎就拿来用了,呵呵,省了我不少时间啊! 其实我们想到的一些新功能,网络早已有之,犹其在中国,很多的创新,其实都是从国外翻译过来的,在代码这方面,老外的脑子确实很好使。上面的函数,作者不 详,但还是要感谢作者的辛苦付出。