简体   繁体   中英

Thumbnail generation time

Idea
I have a function that checks to see if a thumbnail exists in cache folder for a particular image. If it does, it returns the path to that thumbnail. If it does not, it goes ahead and generates the thumbnail for the image, saves it in the cache folder and returns the path to it instead.

Problem
Let's say I have 10 images but only 7 of them have their thumbnails in the cache folder. Therefore, the function goes to generation of thumbnails for the rest 3 images. But while it does that, all I see is a blank, white loading page. The idea is to display the thumbnails that are already generated and then generate the ones that do not exist.

Code

$images = array(
        "http://i49.tinypic.com/4t9a9w.jpg",
        "http://i.imgur.com/p2S1n.jpg",
        "http://i49.tinypic.com/l9tow.jpg",
        "http://i45.tinypic.com/10di4q1.jpg",
        "http://i.imgur.com/PnefW.jpg",
        "http://i.imgur.com/EqakI.jpg",
        "http://i46.tinypic.com/102tl09.jpg",
        "http://i47.tinypic.com/2rnx6ic.jpg",
        "http://i50.tinypic.com/2ykc2gn.jpg",
        "http://i50.tinypic.com/2eewr3p.jpg"
    );

function get_name($source) {
    $name = explode("/", $source);
    $name = end($name);
    return $name;
}

function get_thumbnail($image) {
    $image_name = get_name($image);
    if(file_exists("cache/{$image_name}")) {
        return "cache/{$image_name}";
    } else {
        list($width, $height) = getimagesize($image);
        $thumb = imagecreatefromjpeg($image);
        if($width > $height) {
            $y = 0;
            $x = ($width - $height) / 2;
            $smallest_side = $height;
        } else {
            $x = 0;
            $y = ($height - $width) / 2;
            $smallest_side = $width;
        }

        $thumb_size = 200;
        $thumb_image = imagecreatetruecolor($thumb_size, $thumb_size);
        imagecopyresampled($thumb_image, $thumb, 0, 0, $x, $y, $thumb_size, $thumb_size, $smallest_side, $smallest_side);

        imagejpeg($thumb_image, "cache/{$image_name}");

        return "cache/{$image_name}";
    }
}

foreach($images as $image) {
    echo "<img src='" . get_thumbnail($image) . "' />";
}

To elaborate on @DCoder's comment, what you could do is;

  • If the thumb exists in the cache, return the URL just as you do now. This will make sure that thumbs that are in the cache will load quickly.

  • If the thumb does not exist in the cache, return an URL similar to /cache/generatethumb.php?http://i49.tinypic.com/4t9a9w.jpg where the script generatethumb.php generates the thumbnail, saves it in the cache and returns the thumbnail. Next time, it will be in the cache and the URL won't go through the PHP script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM