难以回显 JPEG 图像


Difficulty Echoing JPEG Images

我在将图像回显到浏览器时遇到了一些困难。我对PHP很陌生,在过去的一个小时里,我一直在网上搜索,但没有找到解决方案。我尝试将header('Content-Type: image/jpeg'); 添加到文档中,但它没有任何作用。我希望我的代码扫描目录并将其所有图像文件放入$thumbArray中,我将回显到浏览器。我的最终目标是建立一个照片库。将图像放入数组中工作正常,但它不会在页面上显示它们。这是我的代码:

  <?php
//Directory that contains the photos
$dir = 'PhotoDir/';
//Check to make sure the directory path is valid
if(is_dir($dir))
{
    //Scandir returns an array of all the files in the directory
    $files = scandir($dir);
}

//Declare array
$thumbArray = Array();
foreach($files as $file)
{
    if ($file != "." && $file != "..")     //Check that the files are images
        array_push($thumbArray, $file);   //array_push will add the $file to thumbarray at index count - 1
}

 print_r($thumbArray);

include 'gallery.html';
?>

下面是图库.html文件:

    <!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Gallery</title>
</head>
<body>

    <?php
    header('Content-Type: image/jpeg'); 
    for($i = 0; $i < count($thumbArray); $i++)
     echo '<img src="$dir'.$thumbArray[$i].'" alt="Picture" />';
    ?>
</body>
</html>

对于您当前的情况,只需从代码中删除header('Content-Type: image/jpeg');即可。您的输出是 HTML。所有图像都输出在IMG标签内。在这种情况下,不需要修改其他标头。

另外,如果你想使用 PHP,不要把这段代码放在 *.html 文件中。它不会在 *.html 中运行,默认的 http 服务器设置。将gallery.html重命名为gallery.php并将include 'gallery.html';更改为include 'gallery.php';,它将正常工作(当然,如果您也删除了header('Content-Type: image/jpeg');)。

第三个坏事是:

echo '<img src="$dir'.$thumbArray[$i].'" alt="Picture" />';

您正在尝试将变量放入单引号$dir。只有双引号允许您在里面使用 PHP 变量。

更改它:

echo '<img src="'.$dir.$thumbArray[$i].'" alt="Picture" />';

更改后,请查看页面的源代码并检查您的图像路径是否正确。如果没有,请执行一些操作来纠正它。例如,也许您忘记了目录分隔符,正确的字符串将是:

echo '<img src="'.$dir.'/'.$thumbArray[$i].'" alt="Picture" />';

等等。