6
The code below aims to provide an image with specific measures to minimize its size and thus optimize the web-site loading.
Problem
The image takes more than 1 second to be provided, making it a considerable weight in the initial web-site loading:
The size collected is 76.5KB but the waiting time for the server is scary being between 800ms and 900ms:
Original image
If you pull the original image, it takes about 430ms to 160.7KB.
PHP code
The code below receives the width and height of the screen.
Prepares the image for incoming measurements and returns it to the browser:
ob_start("ob_gzhandler");
$file = "bg_body.jpg";
if (is_file($file)) {
$source_image = imagecreatefromjpeg($file);
$source_imagex = $dest_imagex = imagesx($source_image);
$source_imagey = $dest_imagey = imagesy($source_image);
if (isset($_GET["w"]) && ctype_digit($_GET["w"])) {
$dest_imagex = $_GET["w"];
}
if (isset($_GET["h"]) && ctype_digit($_GET["h"])) {
$dest_imagey = $_GET["h"];
}
$dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);
imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);
header("Content-Type: image/jpeg");
imagejpeg($dest_image,NULL,70);
} else {
echo "Image file not found!";
}
ob_end_flush();
Question
How can I optimize this code with the ultimate aim of reducing the time it takes to generate the image to send to the browser?
I think at the time of sending is more appropriate. The user already expects that uploading anything will be time consuming, regardless of the speed of your connection. But realizing delay in viewing the image may end up getting the wrong impression as to the stability of the site or server.
– Bruno Augusto
@Brunoaugusto I agree that it is usually better. Only in very specific cases do not find necessary. For example, if it is an intranet system or for restricted use by a group of users, because then they will be more concerned with functionality than with these details and no one will make a point of paying for a super HD.
– utluiz
I think the solution is really going to change the backend and leave images with ranges of sizes to avoid this problem. + 1 By suggestion and comparison with one of "cavalry" :) I’ll wait however to see if anyone points out any flaw in the code that might be behind the delay... I still think that more than 1 second to resize an image is too long!
– Zuul
@Zuul I haven’t worked with PHP image manipulation for some time, but from what I remember and from a brief search I did, there doesn’t seem to be anything in this code to be optimized. The delay problem may be in process priority, processor capacity or lack of acceleration by hardware (graphics card offboard).
– utluiz