The code below aims to provide an image with specific measures to minimize its size and thus optimize web-site loading.
Problem
The image takes more than 1 second to render, making it a heavy load on the initial upload of the web-site:
The collected size is 76.5KB but the wait time by 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 the received 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 goal of reducing the time it takes to generate the image to send to the browser?