2011-05-19 80 views
0

我想用php腳本顯示圖像。這是我目前的代碼:如何返回圖像

<?php 
if (isset ($_GET['id'])) $id = $_GET['id']; 
$t=getimagesize ($id) or die('Unknown type of image'); 

switch ($t[2]) 
{ 
    case 1: 
    $type='GIF'; 
    $img=imagecreatefromgif($path); 
    break; 
    case 2: 
    $type='JPEG'; 
    $img=imagecreatefromjpeg($path); 
    break; 
    case 3: 
    $type='PNG'; 
    $img=imagecreatefrompng($path); 
    break; 
} 

header("Content-type: image/".$type); 
echo $img; 
?> 

但它不顯示圖像。什麼是正確的方式,而不是echo $img

回答

1
header("Content-type: image/jpeg"); 
imagejpeg($img); 
+0

' 警告:imagejpeg():提供的參數不是有效的圖像資源'到你的代碼的第二行 – Ockonal 2011-05-19 12:16:22

+0

該問題詢問**返回**圖像...恕我直言,這傢伙的答案是去:[鏈接](https://stackoverflow.com/questions/22266402/how-to-encode-an-image-resource-to-base64)...結合這另一個[鏈接](https:// stackoverflow.com/questions/8499633/how-to-display-base64-images-in-html)必須完成這項工作。 – Nowdeen 2017-07-25 13:16:39

0

我之前使用過echo(),它已經工作了。但是請嘗試使用imagejpeg()函數。

此外,請確保在腳本中的圖像之前或之後沒有輸出任何其他內容。一個常見的問題是在<?php?>標籤之前或之後由空格和換行符引起的空格和換行輸出。你需要刪除所有這些。並檢查通過include()requre()加載的任何其他PHP代碼的相同的東西。

2

就像這樣:

public function getImage() 
{ 

    $imagePath ="img/wall_1.jpg"; 

    $image = file_get_contents(imagePath); 
      header('content-type: image/gif'); 
      echo $image; 

}