簡體   English   中英

PHP圖像上傳失敗,並使用imagecreatefromjpeg處理png和bmp文件?

[英]Php Image upload failing and using imagecreatefromjpeg to process png and bmp files?

您好,我有以下代碼來創建圖像的縮略圖,然后上傳。 當我嘗試上傳以下附件的圖像時,代碼失敗,並且我不知道為什么。 在此代碼之前,有一個主圖像上載始終有效,但是上面的縮略圖腳本在大多數情況下都起作用,但由於某些原因不帶有附加圖像。 代碼消失,因此頁面輸出成功的主圖像上傳,但是縮略圖從不上傳,頁面的其余部分也不上傳。

此代碼還會處理除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 );

圖片失敗

您的代碼對我來說適合您的圖像,因此問題必須出在輸入變量的設置值上。

如注釋中所建議,請檢查您的PHP錯誤日志。 如果那沒有顯示任何異常,則需要逐行調試代碼。

對於問題的第二部分:不,您的代碼不適用於JPEG以外的其他圖像。 下面的更改將處理GIF,JPEG和PNG。

請注意,函數exif_imagetype()可能默認情況下不可用。 在這種情況下,您需要在PHP配置中激活exif擴展

$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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM