2013-02-03 140 views
0

理念
我有检查,看看是否在cache文件夹中存在的特定图像的缩略图的功能。如果确实如此,则返回到该缩略图的路径。如果不是,则继续并生成图像的缩略图,将其保存在cache文件夹中,并将路径返回给它。缩略图生成时间

问题
比方说,我有10幅图像,但只有7人有自己的缩略图在cache文件夹中。因此,该功能将生成其余3张图像的缩略图。但是,尽管如此,我看到的只是一个空白的白色加载页面。这个想法是显示已经生成的缩略图,然后生成不存在的缩略图。

代码

$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) . "' />"; 
} 
+3

不要生成拇指抢先。将请求重定向到不存在的大拇指,以便在需要时生成它们的PHP脚本。 – DCoder

+0

@DCoder:我明白了。如果可能的话,你能给我一个代码示例吗?我不知道如何去做你刚刚说的话。 #Beginner – Rafay

回答

2

为了详细说明@ DCoder的评论,你可以做的是什么;

  • 如果拇指存在于缓存中,则返回URL,就像现在一样。这将确保缓存中的大拇指将快速加载。

  • 如果拇指不缓存中,返回类似/cache/generatethumb.php?http://i49.tinypic.com/4t9a9w.jpg的URL在脚本generatethumb.php生成缩略图,在缓存中保存并返回缩略图。下一次,它将在缓存中,并且URL不会通过PHP脚本。

+0

+1 - 正是我想到的,有一个警告 - 我宁愿为每个图像生成一个唯一的标识符,并将* *传递给'generatethumb.php'而不是完整的URL,或者使用域白名单。如果有人请求“http://yoursite.com/cache/generatethumb.php?http://yoursite.com/cache/generatethumb.php?http://yoursite.com”,则传递完整的URL可以为您提供“有趣”的结果/cache/generatethumb.php ...' – DCoder

+0

嘿,非常感谢!这正是我想要做的。也感谢@DCoder。虽然我还有一个问题:一旦缩略图生成并保存在目录中,它会在网页上显示一个[X]符号(该符号指的是“未找到图像”)。什么是补救这个问题的好办法? – Rafay

+0

@直播好点,没有任何控制的情况下盲目获取URL并不是一件好事。至少,您应该检查URL是否请求图像类型,如jpg。 –