本文實例講述了php生成高清縮略圖的方法。分享給大家供大家參考,具體如下:
在使用php的函數生成縮略圖的使用,縮略圖很多情況下都會失真,這個時候需要有一些對應的解決方法。
1.用imagecreatetruecolor和imageCopyreSampled函數分別取代imagecreate和imagecopyresized
2.給imagejpeg的第三個參數帶上100(例:imagejpeg($ni,$toFile,100))
下面是具體的函數
function CreateSmallImage( $OldImagePath, $NewImagePath, $NewWidth=154, $NewHeight=134) { // 取出原圖,獲得圖形信息getimagesize參數說明:0(寬),1(高),2(1gif/2jpg/3png),3(width="638" height="340") $OldImageInfo = getimagesize($OldImagePath); if ( $OldImageInfo[2] == 1 ) $OldImg = @imagecreatefromgif($OldImagePath); elseif ( $OldImageInfo[2] == 2 ) $OldImg = @imagecreatefromjpeg($OldImagePath); else $OldImg = @imagecreatefrompng($OldImagePath); // 創建圖形,imagecreate參數說明:寬,高 $NewImg = imagecreatetruecolor( $NewWidth, $NewHeight ); //創建色彩,參數:圖形,red(0-255),green(0-255),blue(0-255) $black = ImageColorAllocate( $NewImg, 0, 0, 0 ); //黑色 $white = ImageColorAllocate( $NewImg, 255, 255, 255 ); //白色 $red = ImageColorAllocate( $NewImg, 255, 0, 0 ); //紅色 $blue = ImageColorAllocate( $NewImg, 0, 0, 255 ); //藍色 $other = ImageColorAllocate( $NewImg, 0, 255, 0 ); //新圖形高寬處理 $WriteNewWidth = $NewHeight*($OldImageInfo[0] / $OldImageInfo[1]); //要寫入的高度 $WriteNewHeight = $NewWidth*($OldImageInfo[1] / $OldImageInfo[0]); //要寫入的寬度 //這樣處理圖片比例會失調,但可以填滿背景 if ($OldImageInfo[0] / $NewWidth > $org_info[1] / $NewHeight) { $WriteNewWidth = $NewWidth; $WriteNewHeight = $NewWidth / ($OldImageInfo[0] / $OldImageInfo[1]); } else { $WriteNewWidth = $NewHeight * ($OldImageInfo[0] / $OldImageInfo[1]); $WriteNewHeight = $NewHeight; } //以$NewHeight為基礎,如果新寬小於或等於$NewWidth,則成立 if ( $WriteNewWidth <= $NewWidth ) { $WriteNewWidth = $WriteNewWidth; //用判斷後的大小 $WriteNewHeight = $NewHeight; //用規定的大小 $WriteX = floor( ($NewWidth-$WriteNewWidth) / 2 ); //在新圖片上寫入的X位置計算 $WriteY = 0; } else { $WriteNewWidth = $NewWidth; // 用規定的大小 $WriteNewHeight = $WriteNewHeight; //用判斷後的大小 $WriteX = 0; $WriteY = floor( ($NewHeight-$WriteNewHeight) / 2 ); //在新圖片上寫入的X位置計算 } //舊圖形縮小後,寫入到新圖形上(復制),imagecopyresized參數說明:新舊, 新xy舊xy, 新寬高舊寬高 @imageCopyreSampled( $NewImg, $OldImg, $WriteX, $WriteY, 0, 0, $WriteNewWidth, $WriteNewHeight, $OldImageInfo[0], $OldImageInfo[1] ); //保存文件 // @imagegif( $NewImg, $NewImagePath ); @imagejpeg($NewImg, $NewImagePath, 100); //結束圖形 @imagedestroy($NewImg); } CreateSmallImage("./images/jiexie.jpg","./images/jiexie.small.jpg",200,300); CreateSmallImage("./images/jiexie.jpg","./images/jiexie.middle.jpg",400,500);
希望本文所述對大家php程序設計有所幫助。