Reputation: 181
How can I make these images load faster? I have a loop that displays a profiles pictures and the photos take 1 to 2.5 seconds to load. Not one after another but pretty much all at once. I tried re-sizing with PHP but that didn't really change anything. I am not sure how I can pre-load these images with such a loop. What can I do to increase load performance?
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%;
}
photoprocess.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;
I also have extension checks as "if statements" but those can't be slowing it down this much.
Upvotes: 2
Views: 7123
Reputation: 116180
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.
Upvotes: 0
Reputation: 449783
This part
$image = imagecreatefromjpeg('userphotos/'.$photoid.''.$ext.'');
$imagearray = imagejpeg($image, null);
shouldn't be necessary* and is going to be heavy on the server. You're loading (decoding) and saving (re-encoding) the image for no apparent reason.
Use something like fpasshtru()
:
$name = 'userphotos/'.$photoid.''.$ext.'';
$fp = fopen($name, 'rb');
header('Content-type: image/jpeg');
fpassthru($fp);
Or just link directly to the image. Unless you do some security checks or something, or the images are stored outside the web root, there is no need to go through PHP at all here.
* = unless you have a very specific use case like removing EXIF data from the stored images. In which case you should use some form of caching.
Upvotes: 4