在php中显示图像

时间:2013-08-25 05:56:07

标签: php image

如何通过从mysql数据库中检索图像来显示html中的图像。

我有以下代码,但只显示文本代替图像。 如何显示图像而不是图像文本。

代码:

while ($row = mysql_fetch_assoc($result))
{
    //echo "<div>";
    //echo "<div class=\"slide-image\">";
    print $row['Image'];
    //echo "</div>";
    echo "<div class=\"slide-text\">";
    echo $row['Head'];
    echo $row['Description'];
    //echo "</div>";
    //echo "</div>";
}

它将生成的JPEG显示为文本,您可能会想到这很难解释。

2 个答案:

答案 0 :(得分:3)

您必须使用PHP设置Content-Type标头。如果是JPEG,则为image/jpeg。您可以使用以下命令进行设置:

header('Content-Type: image/jpeg');

请务必在输出任何数据之前设置该标题。

更新

但是当您从同一文档输出图像数据和文本数据时,在您的文件中,您无法将其标题类型设置为多种类型。

一个选项是

while ($row = mysql_fetch_assoc($result))
{
    echo "<div>";
    echo "<div class=\"slide-image\">";
    echo "<img src='image_render.php?id=".$row['some_key_for_record']."'";
    //print $row['Image']; we are moving it to an external page
    echo "</div>";
    echo "<div class=\"slide-text\">";
    echo $row['Head'];
    echo $row['Description'];
    echo "</div>";
    echo "</div>";
}

和image_render.php

 //code to pull data from db according to $_GET['id'];
 header('Content-Type: image/jpeg');
 print $row['Image'];
 //no text data to be output from here

答案 1 :(得分:1)

如果您正在MYSQL table中屏蔽图像源(完整路径),那么您就可以像在html html img中一样打印php中的div标记。你可以这样做,

 while ($row = mysql_fetch_assoc($result))
    {
        //echo "<div>";
        //echo "<div class=\"slide-image\">";
        echo '<img src='".$row['Image']."' width="100" height="100" />';
        //echo "</div>";
        echo "<div class=\"slide-text\">";
        echo $row['Head'];
        echo $row['Description'];
        //echo "</div>";
        //echo "</div>";
    }

注意: 如果您只想在网页中显示图片,则可以使用header('Content-Type: image/jpeg');

执行此操作