标签:
有时上传图片时因为图片太大了,不仅占用空间,消耗流量,而且影响浏(图片的尺寸大小不一)。下面分享一种等比例不失真缩放图片的方法,这样,不管上传的图片尺有多大,都会自动压缩到我们设置尺寸值的范围之内。经过测试,证明实用。
01 |
<?php |
02 |
function resizeImage($im,$maxwidth,$maxheight,$name,$filetype) |
03 |
{ |
04 |
$pic_width = imagesx($im); |
05 |
$pic_height = imagesy($im); |
06 |
|
07 |
if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) |
08 |
{ |
09 |
if($maxwidth && $pic_width>$maxwidth) |
10 |
{ |
11 |
$widthratio = $maxwidth/$pic_width; |
12 |
$resizewidth_tag = true; |
13 |
} |
14 |
|
15 |
if($maxheight && $pic_height>$maxheight) |
16 |
{ |
17 |
$heightratio = $maxheight/$pic_height; |
18 |
$resizeheight_tag = true; |
19 |
} |
20 |
|
21 |
if($resizewidth_tag && $resizeheight_tag) |
22 |
{ |
23 |
if($widthratio<$heightratio) |
24 |
$ratio = $widthratio; |
25 |
else |
26 |
$ratio = $heightratio; |
27 |
} |
28 |
|
29 |
if($resizewidth_tag && !$resizeheight_tag) |
30 |
$ratio = $widthratio; |
31 |
if($resizeheight_tag && !$resizewidth_tag) |
32 |
$ratio = $heightratio; |
33 |
|
34 |
$newwidth = $pic_width * $ratio; |
35 |
$newheight = $pic_height * $ratio; |
36 |
|
37 |
if(function_exists("imagecopyresampled")) |
38 |
{ |
39 |
$newim = imagecreatetruecolor($newwidth,$newheight);//PHP系统函数 |
40 |
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数 |
41 |
} |
42 |
else |
43 |
{ |
44 |
$newim = imagecreate($newwidth,$newheight); |
45 |
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height); |
46 |
} |
47 |
|
48 |
$name = $name.$filetype; |
49 |
imagejpeg($newim,$name); |
50 |
imagedestroy($newim); |
51 |
} |
52 |
else |
53 |
{ |
54 |
$name = $name.$filetype; |
55 |
imagejpeg($im,$name); |
56 |
} |
57 |
} |
58 |
//使用方法: |
59 |
$im=imagecreatefromjpeg("./20140416103023202.jpg");//参数是图片的存方路径 |
60 |
$maxwidth="600";//设置图片的最大宽度 |
61 |
$maxheight="400";//设置图片的最大高度 |
62 |
$name="123";//图片的名称,随便取吧 |
63 |
$filetype=".jpg";//图片类型 |
64 |
resizeImage($im,$maxwidth,$maxheight,$name,$filetype);//调用上面的函数 |
处理前图片大小:1187*846
图片处理后大小:561*400
处理后的图片名称:123.jpg
写 在最后:因为客户要求使用php实现等比例不失真缩放上传图片,本来要自己写的,但百度一下发现了这个函数,于是乎就拿来用了,呵呵,省了我不少时间啊! 其实我们想到的一些新功能,网络早已有之,犹其在中国,很多的创新,其实都是从国外翻译过来的,在代码这方面,老外的脑子确实很好使。上面的函数,作者不 详,但还是要感谢作者的辛苦付出。
标签:
原文地址:http://www.cnblogs.com/kekjiuyue/p/5831893.html