如何输出图像数组


How to output an array of images?

我试图在以下代码中列出(也重新调整大小)照片。我想输出所有id为x的图像。

问题是我有一个标题,我已经包含在文档中,所以我不能使用header('Content-type: image/jpeg');来输出我想要显示的图像数组。但如果我把它拿出来,它只会显示一堆随机字符,我知道这是一个字符串中的照片。我不知道该怎么做。我还打算让每张照片都有自己的div。

<!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <?php include 'topheader.php'; ?>
        </head>
        <body>
            <?php
                ob_start();
                ini_set("gd.jpeg_ignore_warning", 1);
                $roomid = $_GET['room'];
                $query = "SELECT `photoname` FROM `roomsite`.`photos` WHERE `roomid`='$roomid'";
                $getphotos = $connect->prepare($query);
                if ($getphotos->execute()){
                    while ($array = $getphotos->fetch(PDO::FETCH_ASSOC)){
                        $image = imagecreatefromjpeg('userphotos/'.$array['photoname'].'');

                        list($image_width, $image_height, $type, $attr) = getimagesize('userphotos/'.$array['photoname'].'');
                        $new_size = ($image_width + $image_height)/($image_width*($image_height/100));
                        $new_width = $image_width * $new_size;
                        $new_height = $image_height * $new_size;
                        $new_image = imagecreatetruecolor($new_width, $new_height);
                        imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
                        $imagearray = imagejpeg($new_image, null);
                        header('Content-type: image/jpeg'); 
                        echo $imagearray;

                    }
                } else { die('Query Error'); }
            ?>
        </body>

    </html> 

我可以这样做

while ($array = $getphotos->fetch(PDO::FETCH_ASSOC)){
   echo '<img src="outputphotos.php">';
}

但这意味着我将运行查询两次,这可能不是一个好主意?这是唯一的办法吗?

HTTP协议对一个问题处理一个答案。HTML的工作方式是在单个HTML文档中描述结构和内容,并允许通过引用加载辅助资源。正确的方法是在你的HTML中生成img标签,以显示需要显示的图片,也允许你对它们进行样式设置等。在引用的url中,您可以为特定的图像提供参数。

伪代码:

while($row = $myQuery->nextRow())
    echo '<img src="/showimage.php?id='.$row->getId().
         ' alt="'.htmlentities($row->getName()).'">';

由于图像从定义上讲是独立文件,因此您不能以任何方式将它们发送到与引用文档相同的请求中。

如果您确实需要动态调整图像大小,您可以为此编写单独的脚本。比如:

http://yourdomain.com/DynamicImage.php?image=foo.png&maxwidth=100&maxheight=100

然后将所有IMG标签路由到那里:

<img src="http://yourdomain.com/DynamicImage.php?image=originalImageName.jpg&maxwidth=100&maxheight=100" />

您可以教脚本缓存结果调整大小的图像,并在将来的请求中直接提供它们。