两年前,Chris Coyier 撰写了一篇出色的教程,详细介绍了如何根据两个目录中的图像生成照片库:缩略图目录和原件目录。我决定通过向您展示如何使用 PHP 为画廊生成缩略图,使他的教程更进一步。我还实现了一个 MooTools 灯箱:Smoothbox。以下代码将向您展示如何通过简单地将照片转储到目录中来创建漂亮的照片库。
CSS
.clear { clear:both; } .photo-link { padding:5px; margin:5px; border:1px solid #ccc; display:block; width:200px; float:left; } .photo-link:hover { border-color:#999; }
图像/链接将彼此相邻浮动。另一种选择是使用表格。呜呜呜。
PHP:效用函数
/* function: generates thumbnail */ function make_thumb($src,$dest,$desired_width) { /* read the source image */ $source_image = imagecreatefromjpeg($src); $width = imagesx($source_image); $height = imagesy($source_image); /* find the "desired height" of this thumbnail, relative to the desired width */ $desired_height = floor($height*($desired_width/$width)); /* create a new, "virtual" image */ $virtual_image = imagecreatetruecolor($desired_width,$desired_height); /* copy source image at a resized size */ imagecopyresized($virtual_image,$source_image,0,0,0,0,$desired_width,$desired_height,$width,$height); /* create the physical thumbnail image to its destination */ imagejpeg($virtual_image,$dest); } /* function: returns files from dir */ function get_files($images_dir,$exts = array('jpg')) { $files = array(); if($handle = opendir($images_dir)) { while(false !== ($file = readdir($handle))) { $extension = strtolower(get_file_extension($file)); if($extension && in_array($extension,$exts)) { $files[] = $file; } } closedir($handle); } return $files; } /* function: returns a file's extension */ function get_file_extension($file_name) { return substr(strrchr($file_name,'.'),1); }
我们将使用三个实用函数来使系统正常工作:get_files(检索给定目录中的所有文件)、get_file_extension 和 make_thumb(从源图像生成缩略图图像)。这些都是很好的功能,也可以用于其他目的。
PHP:设置和 HTML 生成
/** settings **/ $images_dir = 'preload-images/'; $thumbs_dir = 'preload-images-thumbs/'; $thumbs_width = 200; $images_per_row = 3; /** generate photo gallery **/ $image_files = get_files($images_dir); if(count($image_files)) { $index = 0; foreach($image_files as $index=>$file) { $index++; $thumbnail_image = $thumbs_dir.$file; if(!file_exists($thumbnail_image)) { $extension = get_file_extension($thumbnail_image); if($extension) { make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width); } } echo '<a href="',$images_dir.$file,'" rel="gallery"><img src="',$thumbnail_image,'" /></a>'; if($index % $images_per_row == 0) { echo '<div ></div>'; } } echo '<div ></div>'; } else { echo '<p>There are no images in this gallery.</p>'; }
第一步是定义一些简单的设置,这些设置将指示图像路径、创建所有缩略图的宽度以及每行的图像数量。该操作从收集所有文件开始。对于画廊中的每张图片,我们都会检查缩略图是否存在。如果缩略图不存在,我们使用 PHP 和上面的实用函数来生成一个。当缩略图生成时(或者一开始就有缩略图),我们输出 HTML 链接/图像。我已经为 A 元素提供了“smoothbox”CSS 类,这样 Smoothbox 就会在灯箱中显示更大的图像。
MooTools JavaScript / Smoothbox
您需要做的就是包含 JavaScript 文件。甜蜜。
就是这样!有任何您希望添加的功能吗?让我知道!