2015-10-17 47 views
3

有人知道這段代碼有什麼問題嗎?它不給我一個實際的圖像,它給我一個圖像錯誤。我認爲我正確設置了所有功能和一切。任何建議都會很棒。試圖使用PHP調整圖像大小

<?php 
function resizeImage($filename, $max_width, $max_height) { 
    list($orig_width, $orig_height) = getimagesize($filename); 

    $width = $orig_width; 
    $height = $orig_height; 

    # taller 
    if ($height > $max_height) { 
    $width = ($max_height/$height) * $width; 
    $height = $max_height; 
    } 

    # wider 
    if ($width > $max_width) { 
    $height = ($max_width/$width) * $height; 
    $width = $max_width; 
    } 

    $image_p = imagecreatetruecolor($width, $height); 

    $image = imagecreatefromjpeg($filename); 

    imagecopyresampled($image_p, $image, 0, 0, 0, 0, 
        $width, $height, $orig_width, $orig_height); 

    return $image_p; 
} 

$directory = "uploads/"; 
$images = glob($directory."*"); 

foreach($images as $image) { 

    // Set a maximum height and width 
    $width = 200; 
    $height = 200; 
    $newImage = resizeImage($image, $width, $height); 

    echo '<img src="'.$newImage.'" /><br />'; 
}  
?> 
+0

哦,我必須保存調整大小的圖像一些地方? –

+0

如果您必須只顯示一個圖像,則不需要。但在這裏你在同一頁面顯示多個圖像。 –

+0

@JaeKim:如果你不想保存圖片,請檢查我的答案。 –

回答

1

如果你不想保存圖像,那麼你可以使用下面的代碼。

<?php 
    function resizeImage($filename, $max_width, $max_height) { 
     list($orig_width, $orig_height) = getimagesize($filename); 

     $width = $orig_width; 
     $height = $orig_height; 

     # taller 
     if ($height > $max_height) { 
      $width = ($max_height/$height) * $width; 
      $height = $max_height; 
     } 

     # wider 
     if ($width > $max_width) { 
      $height = ($max_width/$width) * $height; 
      $width = $max_width; 
     } 

     $image_p = imagecreatetruecolor($width, $height); 
     $image = imagecreatefromjpeg($filename); 
     imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $orig_width, $orig_height); 
     ob_start(); 
     imagejpeg($image_p); 
     $imgSrc = 'data:image/jpeg;base64,'.base64_encode(ob_get_clean()); 
     return $imgSrc; 
    } 

    $directory = "uploads/"; 
    $images = glob($directory."*"); 

    foreach($images as $image) { 
     // Set a maximum height and width 
     $width = 200; 
     $height = 200; 
     $imgSrc = resizeImage($image, $width, $height); 
     echo '<img src="'.$imgSrc.'" /><br />'; 
    }  
?> 

,如果你想保存的圖片,那麼你必須創建一些其他文件夾一樣resized並保存截取圖像存在,並將其鏈接爲如下。(不改變你的舊代碼,並添加本)

<?php  
    $directory = "uploads/"; 
    $images = glob($directory."*"); 

    $i=1;//added 
    foreach($images as $image) { 
     // Set a maximum height and width 
     $width = 200; 
     $height = 200; 
     $newImage = resizeImage($image, $width, $height); 
     imagejpeg($newImage,"resized/newimage".$i.".jpg"); //added 
     echo '<img src="resized/newimage'.$i.'.jpg" /><br />';//modified 
     $i++;//added 
    }  
?> 
+0

'$ imgSrc ='data:image/jpeg; base64,'。base64_encode(ob_get_clean());'這個工作嗎? –

+0

是的,它獲取當前的緩衝區內容並刪除當前的輸出緩衝區。 http://php.net/manual/en/function.ob-get-clean.php –