2

如何使这些图像加载更快?我有一个显示个人资料图片的循环,这些照片需要 1 到 2.5 秒才能加载。不是一个接一个,而是几乎同时发生。我尝试使用 PHP 重新调整大小,但这并没有真正改变任何东西。我不确定如何使用这样的循环预加载这些图像。我可以做些什么来提高负载性能?

PHP

$query = "SELECT `photoid` FROM `site`.`photos` WHERE `profileid`='$profileid'";
         try{
    $getphotos = $connect->prepare($query);
    $getphotos->execute();
    while ($array = $getphotos->fetch(PDO::FETCH_ASSOC)){
         echo '<div id="photo"><img src="photoprocess.php?photo='.$array['photoid'].'"></div>';
    }
    } catch (PDOException $e) {
         echo $e->getMessage();
    }

CSS

#photo img {
    max-width:100%; 
    max-height:100%;
}

照片处理.php

       $photoid = $_GET['photo'];

    $query = "SELECT `ext` FROM `site`.`photos` WHERE `photoid`='$photoid'";
        try{
            $getphotos = $connect->prepare($query);
            $getphotos->execute();
            $array = $getphotos->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }   

         $ext = $array['ext'];

        $image = imagecreatefromjpeg('userphotos/'.$photoid.''.$ext.'');
        $imagearray = imagejpeg($image, null);

        header('Content-type: image/jpeg'); 
            echo $imagearray;

我也有扩展检查作为“if 语句”,但这些不能让它减慢这么多。

4

2 回答 2

4

这部分

    $image = imagecreatefromjpeg('userphotos/'.$photoid.''.$ext.'');
    $imagearray = imagejpeg($image, null);

不应该是必要的*并且会在服务器上很重。您无缘无故地加载(解码)和保存(重新编码)图像。

使用类似的东西fpasshtru()

$name = 'userphotos/'.$photoid.''.$ext.'';
$fp = fopen($name, 'rb');

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

fpassthru($fp);

或者直接链接到图像。除非您进行一些安全检查或其他操作,或者图像存储在 Web 根目录之外,否则这里根本不需要通过 PHP。

* = 除非您有非常具体的用例,例如从存储的图像中删除 EXIF 数据。在这种情况下,您应该使用某种形式的缓存。

于 2013-07-07T22:03:09.273 回答
0

Currently, you are loading image data from disk into an image buffer, which is validated by PHP. After that, you re-encode the image data to a jpg image buffer again and output it. This is useless. You can just load an thruput the file (read about fpassthru). This is also much more memory efficient, since the image doesn't need to be entrely loaded in memory entirely at once.

That will be way, way faster, but it can be faster still, because I think you can use just .htaccess to redirect an url with an image id to the actual image. You don't even need PHP for that.

于 2013-07-07T22:06:51.210 回答