2014-10-30 112 views
-1

你好,我有以下代碼來創建一個圖像的縮略圖,然後上傳它。當我嘗試上傳下面附加的圖片時,代碼失敗,我不知道爲什麼。在此代碼之前,有一個主要圖像上傳總是有效的,但上面的縮略圖腳本在大多數情況下都能正常工作,但由於某些原因不會附加圖像。代碼死了,所以頁面輸出主要圖片上傳的成功,但縮略圖從未上傳,頁面的其餘部分也沒有。Php圖片上傳失敗,並使用imagecreatefromjpeg來處理PNG和BMP文件?

此代碼還會處理jpeg以外的圖像嗎?如果它不會如何去處理像bmp和png這樣的其他文件類型?

// load image and get image size 
    $img = imagecreatefromjpeg($upload_path . $filename); 
    $width = imagesx($img); 
    $height = imagesy($img); 

    // calculate thumbnail size 
    $new_height = $thumbHeight; 
    $new_width = floor($width * ($thumbHeight/$height)); 

    // create a new temporary image 
    $tmp_img = imagecreatetruecolor($new_width, $new_height); 

    // copy and resize old image into new image 
    imagecopyresized($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

    // save thumbnail into a file 
    imagejpeg($tmp_img, $upload_paththumbs . $filename); 

Image that fails

+2

請解釋一下你的*「的代碼失敗」 * – Phil 2014-10-30 02:35:53

+0

在此之前的代碼中有一個主要的圖片上傳總是工作,但上面的縮略圖腳本工作的大部分時間,但無法與安裝的圖像是什麼意思因爲某些原因。代碼死了,所以頁面輸出主要圖片上傳的成功,但縮略圖從未上傳,頁面的其餘部分也沒有。 – Munnaz 2014-10-30 02:41:26

+0

聽起來像你沒有看到錯誤。在你的'php.ini'文件來實現正確的錯誤報告'的error_reporting = E_ALL'和'的display_errors = On'並重新啓動Web服務器 – Phil 2014-10-30 02:43:30

回答

0

您的代碼對我的作品與你的形象,所以這個問題必須與您輸入變量的設定值。

正如評論中的建議,檢查你的PHP錯誤日誌。如果沒有顯示任何異常,則需要逐行調試代碼。

對於你的問題的第二部分:不,你的代碼也不會比JPEG圖像等工作。下面的更改將處理GIF,JPEG和PNG。

注意,功能exif_imagetype()可能不會被默認使用。在這種情況下,您需要在您的PHP配置中使用activate the exif extension

$upload_path = './'; 
$filename = 'b4bAx.jpg'; 
$upload_paththumbs = './thumb-'; 
$thumbHeight = 50; 

switch (exif_imagetype($upload_path . $filename)) { 
    case IMAGETYPE_GIF: 
     imagegif(
      thumb(imagecreatefromgif($upload_path . $filename), $thumbHeight), 
      $upload_paththumbs . $filename 
     ); 
     break; 
    case IMAGETYPE_JPEG: 
     imagejpeg(
      thumb(imagecreatefromjpeg($upload_path . $filename), $thumbHeight), 
      $upload_paththumbs . $filename 
     ); 
     break; 
    case IMAGETYPE_PNG: 
     imagepng(
      thumb(imagecreatefrompng($upload_path . $filename), $thumbHeight), 
      $upload_paththumbs . $filename 
     ); 
     break; 
    default: 
     echo 'Unsupported image type!'; 
} 

function thumb($img, $thumbHeight) { 
    // get image size 
    $width = imagesx($img); 
    $height = imagesy($img); 

    // calculate thumbnail size 
    $new_height = $thumbHeight; 
    $new_width = floor($width * ($thumbHeight/$height)); 

    // create a new temporary image 
    $tmp_img = imagecreatetruecolor($new_width, $new_height); 

    // copy and resize old image into new image 
    imagecopyresampled($tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height); 

    // return thumbnail 
    return $tmp_img; 
}