<?php /** * *函數(shù):調(diào)整圖片尺寸或生成縮略圖 *修改:2013-2-15 *返回:True/False *參數(shù): * $Image 需要調(diào)整的圖片(含路徑) * $Dw=450 調(diào)整時最大寬度;縮略圖時的絕對寬度 * $Dh=450 調(diào)整時最大高度;縮略圖時的絕對高度 * $Type=1 1,調(diào)整尺寸; 2,生成縮略圖 */ $phtypes=array('img/gif', 'img/jpg', 'img/jpeg', 'img/bmp', 'img/pjpeg', 'img/x-png'); function compressImg($Image,$Dw,$Dh,$Type){ IF(!file_exists($Image)){ return false; } // 如果需要生成縮略圖,則將原圖拷貝一下重新給$Image賦值(生成縮略圖操作) // 當(dāng)Type==1的時候,將不拷貝原圖像文件,而是在原來的圖像文件上重新生成縮小后的圖像(調(diào)整尺寸操作) IF($Type!=1){ copy($Image,str_replace(".","_x.",$Image)); $Image=str_replace(".","_x.",$Image); } // 取得文件的類型,根據(jù)不同的類型建立不同的對象 $ImgInfo=getimagesize($Image); Switch($ImgInfo[2]){ case 1: $Img =@imagecreatefromgif($Image); break; case 2: $Img =@imagecreatefromjpeg($Image); Break; case 3: $Img =@imagecreatefrompng($Image); break; } // 如果對象沒有創(chuàng)建成功,則說明非圖片文件 IF(Empty($Img)){ // 如果是生成縮略圖的時候出錯,則需要刪掉已經(jīng)復(fù)制的文件 IF($Type!=1){ unlink($Image); } return false; } // 如果是執(zhí)行調(diào)整尺寸操作則 IF($Type==1){ $w=ImagesX($Img); $h=ImagesY($Img); $width = $w; $height = $h; IF($width>$Dw){ $Par=$Dw/$width; $width=$Dw; $height=$height*$Par; IF($height>$Dh){ $Par=$Dh/$height; $height=$Dh; $width=$width*$Par; } } ElseIF($height>$Dh) { $Par=$Dh/$height; $height=$Dh; $width=$width*$Par; IF($width>$Dw){ $Par=$Dw/$width; $width=$Dw; $height=$height*$Par; } } Else { $width=$width; $height=$height; } $nImg =ImageCreateTrueColor($width,$height);// 新建一個真彩色畫布 ImageCopyReSampled($nImg,$Img,0,0,0,0,$width,$height,$w,$h);// 重采樣拷貝部分圖像并調(diào)整大小 ImageJpeg($nImg,$Image);// 以JPEG格式將圖像輸出到瀏覽器或文件 return true; } Else {// 如果是執(zhí)行生成縮略圖操作則 $w=ImagesX($Img); $h=ImagesY($Img); $width = $w; $height = $h; $nImg =ImageCreateTrueColor($Dw,$Dh); IF($h/$w>$Dh/$Dw){// 高比較大 $width=$Dw; $height=$h*$Dw/$w; $IntNH=$height-$Dh; ImageCopyReSampled($nImg, $Img, 0, -$IntNH/1.8, 0, 0, $Dw, $height, $w, $h); } Else {// 寬比較大 $height=$Dh; $width=$w*$Dh/$h; $IntNW=$width-$Dw; ImageCopyReSampled($nImg, $Img,-$IntNW/1.8,0,0,0, $width, $Dh, $w, $h); } ImageJpeg($nImg,$Image); return true; } }; /** *根據(jù)url獲取服務(wù)器上的圖片 *$url服務(wù)器上圖片路徑 $filename文件名 */ function GrabImage($url,$filename="") { if($url=="") return false; if($filename=="") { $ext=strrchr($url,"."); if($ext!=".gif" && $ext!=".jpg" && $ext!=".png") return false; $filename=date("YmdHis").$ext; } ob_start(); readfile($url); $img = ob_get_contents(); ob_end_clean(); $size = strlen($img); $fp2=@fopen($filename, "a"); fwrite($fp2,$img); fclose($fp2); return $filename; } ?> <?php //網(wǎng)絡(luò)圖片路徑 $imgPath = 'http://news.jingway.cn/images/1382088444437.jpg';//遠(yuǎn)程URL 地址 $tempPath = 'aa/bbs.jpg';//保存圖片路徑 if(is_file($tempPath)){ unlink($tempPath); } $bigImg=GrabImage($imgPath, $tempPath); compressImg($bigImg,70,70,1); ?> </body> </html>
?