2013-03-08 53 views
0

我試圖在PHP中調整圖像大小,如果上傳的圖像太大。我創建了一個函數,應該調整的文件,然後(希望)返回數組 - 除了它不工作:(作爲一個數組返回一個圖像

private function _resizeImage($image, $width = 780, $height = 780) { 

    $imgDetails = GetImageSize($image["tmp_name"]); 

    // Content type 
    //header("Content-Type: image/jpeg"); 
    //header("Content-Disposition: attachment; filename=resized-$image"); 

    // Get dimensions 
    $width_orig = $imgDetails['0']; 
    $height_orig = $imgDetails['1']; 

    $ratio_orig = $width_orig/$height_orig; 

    if ($width/$height > $ratio_orig) { 
     $width = $height*$ratio_orig; 
    } else { 
     $height = $width/$ratio_orig; 
    } 

    // Resample 
    switch ($imgDetails['2']) 
    { 
     case 1: $newImage = imagecreatefromgif($image["tmp_name"]); break; 
     case 2: $newImage = imagecreatefromjpeg($image["tmp_name"]); break; 
     case 3: $newImage = imagecreatefrompng($image["tmp_name"]); break; 
     default: trigger_error('Unsupported filetype!', E_USER_WARNING); break; 
    } 

    if (!$newImage) { 
     // We get errors from PHP's ImageCreate functions... 
     // So let's echo back the contents of the actual image. 
     readfile ($image); 
    } else { 
     // Create the resized image destination 
     $thumb = @ImageCreateTrueColor ($width, $height); 
     // Copy from image source, resize it, and paste to image destination 
     @ImageCopyResampled ($thumb, $newImage, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); 
     // Output resized image 
     //ImageJPEG ($thumb); 
    } 

    // Output 
    $newFile = imagejpeg($thumb, null, 100); 
    return $newFile; 
} 

這是由叫做:

if($imgDetails['0'] > 780 || $imgDetails['1'] < 780) { 
    $file = $this->_resizeImage($file); // Resize image if bigger than 780x780 
} 

但我沒有得到一個對象回來了,我不知道爲什麼。

+0

[imagejpeg](http://php.net/manual/en/function.imagejpeg.php)返回布爾值。不是一個對象。 – 2013-03-08 19:05:39

回答

1

由於Seain在評論中提到,imagejpeg返回一個布爾值。

bool imagejpeg (resource $image [, string $filename [, int $quality ]]) 

Returns TRUE on success or FALSE on failure. 

imagejpeg reference on php.net

此外,你有NULL作爲第二個參數,將作爲原始圖像流輸出圖像。如果要將圖像保存到某處,則需要爲此參數提供一個文件名。

另一個說明 - 你應該打電話imagedestroy($newImage);釋放你從gif/jpeg/png創建圖像時分配的內存。撥打電話號碼imagejpeg後,請執行此操作。

另外我建議你不要使用@運算符來壓制你的錯誤。請嘗試將這些錯誤記錄到錯誤日誌中。壓制會讓你更難調試你的代碼,如果你有壓制的關鍵性錯誤會完全殺死你的腳本,而沒有指出原因。錯誤日誌幫助。

+0

+1感謝您的解釋。 – 2013-03-09 13:52:09

+0

我還是有點困惑。我如何爲新圖像創建$ _FILES對象?我應該手動構建陣列嗎?我該如何運行'imagedestroy'?新的文件名...? – 2013-03-09 13:54:43

+0

在'$ newImage'上調用'imagedestroy',因爲'$ newImage'是您在調用'imagecreatefromjpeg','imagecreatefrompng'或'imagecreatefromgif'時創建的圖像資源標識符。 – ozz 2013-03-09 18:46:11