2011-05-19 81 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; 

}