2012-06-17 34 views
1

我在上傳時從原始jpeg文件生成縮略圖圖像。我實際上可以創建這些縮略圖文件並將其移動到另一個目錄,但問題在於這些縮略圖文件在上傳時只顯示黑色。上傳時生成的縮略圖全部爲黑色

我的代碼。

if(isset($_POST['upload'])){ 
    $img = $_FILES['origin']['name']; 
    move_uploaded_file($_FILES['origin']['tmp_name'], 'image/'.$img); 

    define("SOURCE", 'image/'); 
    define("DEST", 'thumb/'); 
    define("MAXW", 120); 
    define("MAXH", 90); 

    $jpg = SOURCE.$img; 

    if($jpg){ 
     list($width, $height, $type) = getimagesize($jpg); //$type will return the type of the image 

     if(MAXW >= $width && MAXH >= $height){ 
      $ratio = 1; 
     }elseif($width > $height){ 
      $ratio = MAXW/$width; 
     }else{ 
      $ratio = MAXH/$height; 
     } 

     $thumb_width = round($width * $ratio); //get the smaller value from cal # floor() 
     $thumb_height = round($height * $ratio); 

     $thumb = imagecreatetruecolor($thumb_width, $thumb_height); 

     $path = DEST.$img."_thumb.jpg"; 
     imagejpeg($thumb, $path); 

     echo "<img src='".$path."' alt='".$path."' />"; 
    } 
    imagedestroy($thumb); 
} 

和縮略圖文件看起來像這樣:

enter image description here

回答

2

嗯,我剛剛發現我的錯誤。問題是,我使用$jpg = SOURCE.$img;代替$jpg = imagecreatefromjpeg($jpg);,也是我需要將樣本圖像複製到新的縮略圖使用

imagecopyresampled($thumb, $jpg, 0, 0, 0, 0, $thumb_width, $thumb_height, $width, $height); 

然後它的作品!

感謝亞歷克斯爲您的答案,這導致我到這個解決方案。

3

從PHP手冊:

imagecreatetruecolor() returns an image identifier representing a black image of the specified size.

所以,問題是,你實際上是創建這個黑色圖像並保存它。

$thumb = imagecreatetruecolor($thumb_width, $thumb_height);

有關調整方案,請參考this question on stackoverflow