2014-08-31 307 views
0

我有PHP腳本來生成圖像上傳縮略圖,使用PHP GD庫。PHP的GD縮略圖生成圖像像素失真

縮略圖的高度是固定的(在本例中爲240px),其寬度將根據原始圖像的寬高比進行計算。 ex。

$new_height = $thumbHeight; 
$new_width = intval($thumbHeight * $width/$height); 

但是在一些圖像中,輸出縮略圖圖像具有像素失真。下圖顯示了我的問題。

Exaple Image

生成縮略圖輸出圖像()之後,但我想輸出圖像,因爲它是在

我的代碼:

$file = "pic.jpg"; 
$thumbHeight = 240; 
$progressive = false; 

    $img; 
    if(preg_match('/[.](jpg)$/', $file)) { 
     $img = imagecreatefromjpeg($file); 
    } else if (preg_match('/[.](gif)$/', $file)) { 
     $img = imagecreatefromgif($file); 
    } else if (preg_match('/[.](png)$/', $file)) { 
     $img = imagecreatefrompng($file); 
    } else if(preg_match('/[.](jpeg)$/', $file)) { 
     $img = imagecreatefromjpeg($file); 
    } 

$arr_image_details = getimagesize($file); 
$width = $arr_image_details[0]; // width of input image 
$height = $arr_image_details[1]; // height of input image 

$new_height = $thumbHeight; // new thumbnail height 
$new_width = intval($thumbHeight * $width/$height); // new thumbnail width 


$tmp_img = imagecreatetruecolor($new_width, $new_height); 
imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 
if($progressive) imageinterlace($tmp_img, 1); 
imagejpeg($tmp_img, "lag-$file",100); 

imagedestroy($img); 
imagedestroy($tmp_img); 
+0

您是否嘗試過使用'imagecopyresampled'而不是'imagecopyresized'? – 2014-08-31 07:05:02

+0

不,我沒有試過..但是'imagecopyresized'不同.. ..? – 2014-08-31 07:08:08

+0

它通常會使結果更好,圖像比使用'imagecopyresized'更平滑 – 2014-08-31 07:11:57

回答

2

使用imagecopyresampled()函數而不是imagecopyresized()通常會使渲染圖像更平滑,所以在這種情況下可能會是解決方案。

0

使用imagecopyresampled,而不是imagecopyresized做的伎倆..

原因:

imagecopyresized將複製和規模和形象。這使用一個相當原始的算法,往往會產生更多的像素化結果。

imagecopyresampled將複製和縮放和圖像,它使用平滑和像素插值算法,通常會產生更好的結果,然後imagecopyresized以一點cpu使用的代價。