1 <?php 2 function resizeImage($im,$maxwidth,$maxheight,$name,$filetype) 3 { 4 $pic_width = imagesx($im); 5 $pic_height = imagesy($im); 6 7 if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) 8 { 9 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("1.jpg");//参数是图片的存方路径 60 $maxwidth="600";//设置图片的最大宽度 61 $maxheight="400";//设置图片的最大高度 62 $name="123";//图片的名称,随便取吧 63 $filetype=".jpg";//图片类型 64 resizeImage($im,$maxwidth,$maxheight,$name,$filetype);//调用上面的函数