christian
christian

Reputation: 153

how caching is implemented using PHP GD

I want to cache 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?

Upvotes: 3

Views: 2509

Answers (4)

alphadevx
alphadevx

Reputation: 903

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

Upvotes: 1

Pez Cuckow
Pez Cuckow

Reputation: 14422

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);
}

Upvotes: 5

TheHippo
TheHippo

Reputation: 63159

Have you considered using phpThumb? It has tons of options for image generation and caching.

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157913

Save it to disk. Webserver will take care of caching.

Upvotes: 0

Related Questions