- 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字型並安裝。 |