K
K
Kirill Krasin2017-05-11 12:02:26
PHP
Kirill Krasin, 2017-05-11 12:02:26

How to cache dynamic images with PHP?

Good afternoon.
To generate images (status bar, caption), data from MySQL and locally located image templates and used fonts are used.
The image generation process in this code snippet:

$im     = imagecreatefrompng("./bg_2.png");
$over   = imagecreatefrompng("./over.png");
$flag   = imagecreatefrompng("/dist/img/flags/".$country.".png");
$status = imagecreatefrompng("./".$online.".png");

$orange = imagecolorallocate($im, 205,66,43);
$white  = imagecolorallocate($im, 255,255,255);
$green  = imagecolorallocate($im, 0,204,51);
$red    = imagecolorallocate($im, 255,61,61);
$blue   = imagecolorallocate($im, 51,102,255);
$navy   = imagecolorallocate($im, 75,100,111);

imagecopy($im, $over, 0, 0, 0, 0, 468, 60);
imagecopy($im, $flag, 10, 12, 0, 0, 16, 11);
imagecopy($im, $status, 350, 0, 0, 0, 120, 60);

imagettftext($im, 16, 0, 35, 25, $white, $font, $string);
imagettftext($im, 10, 0, 10, 50, $white, $font2, $string5);

header("Content-type: image/png");

imagepng($im);
imagedestroy($im);
imagedestroy($over);
imagedestroy($flag);

The essence of the question is how to properly cache the resulting image (Memcached or alternatives), given that the data update interval in the database is 5 minutes?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Puma Thailand, 2017-05-11
@opium

Just wait on the disk, everything will be cached by itself, this is static

A
Anton, 2017-05-11
@sHinE

You basically have 4 input parameters - country, status (online/offline) and two strings.
The lines you most likely change rarely, the country does not change at all, and the status - quite often.
When changing strings, I would generate two pictures - one offline, the other online, and would store them separately.
Once every 5 minutes - looked into the database and copied the picture with the desired status to the desired location (well, or renamed - but here you need to somehow remember the previous file name / location).

R
Roman Mirilaczvili, 2017-05-11
@2ord

As a suggestion, you can issue an
Expires HTTP header indicating when 5 minutes expires. Then web clients will be able to know when to update the picture.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question