how caching is implemented using PHP GD
I want to cache开发者_Python百科 the images of my gallery. Generating images every pages load using GD uses a lot of memory, So I am planning to create a cache image for the images generated by php script done with GD. What will be the best thing to create cache?
Use something like
$mime_type = "image/png";
$extension = ".png";
$cache_folder = "cache";
$hash = md5($unique . $things . $for . $each . $image);
$cache_filename = $cache_folder . '/' . $hash . $extension;
//Is already it cached?
if($file = @fopen($cache_filename,'rb')) {
header('Content-type: ' . $mime_type);
while(!feof($file)) { print(($buffer = fread($file,4096))); }
fclose($file);
exit;
} else {
//Generage a new image and save it
imagepng($image,$cache_filename); //Saves it to the given folder
//Send image
header('Content-type: ' . $mime_type);
imagepng($image);
}
Have you considered using phpThumb? It has tons of options for image generation and caching.
I don't think you need to do any iteration when reading the file from the cache, a simple call to readfile() is sufficient. E.g:
if (file_exists($image_path)) {
// send the cached image to the output buffer (browser)
readfile($image_path);
}else{
// create a new image using GD functions
...
The full script is here:
http://www.alphadevx.com/a/57-Implementing-an-Image-Cache-for-PHP-GD
Save it to disk. Webserver will take care of caching.
精彩评论