PHP根据URL自动生成缩略图实现方法
本示例介绍了一种基于PHP根据URL自动生成缩略图的实用方案,该功能在实际开发中具有较高的应用价值,供开发者参考使用。具体实现步骤如下。
核心机制在于配置Apache的Rewrite模块,当客户端请求的图片资源在服务器上不存在时,系统会自动触发PHP脚本来创建相应的图片文件。
具体场景示例如下:
原始大图存放于:http://localhost/upload/news/2013/07/21/1.jpg 对应的缩略图预期访问路径为:http://localhost/supload/news/2013/07/21/1.jpg
当访问 http://localhost/supload/news/2013/07/21/1.jpg 时,如图片存在,则显示图片。否则,调用createthumb.php生成图片。
项目所需的目录结构安排如下:
www/PicThumb.class.php www/ThumbConfig.php www/upload/news/2013/07/21/1.jpg www/upload/article/2013/07/21/2.jpg www/supload/.htaccess www/supload/watermark.png www/supload/createthumb.php
其中,http://localhost/ 根目录指向 www文件夹。
关于 PicThumb.class.php 的具体使用方法,可参考链接:https://www.jb51.net/article/55530.htm
此功能依赖于Apache的rewrite模块,需确保该模块已启用:
sudo a2enmod rewrite
.htaccess配置文件内容如下:
RewriteEngine On
# '-s' (is regular file, with size)
# '-l' (is symbolic link)
# '-d' (is directory)
# 'ornext|OR' (or next condition)
# 'nocase|NC' (no case)
# 'last|L' (last rule)
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ createthumb.php?path=%{REQUEST_URI} [NC,L]
createthumb.php 核心逻辑代码如下:
<?php
define('WWW_PATH', dirname(dirname(__FILE__))); // 站点www目录
require(WWW_PATH.'/PicThumb.class.php'); // include PicThumb.class.php
require(WWW_PATH.'/ThumbConfig.php'); // include ThumbConfig.php
$logfile = WWW_PATH.'/createthumb.log'; // 日志文件
$source_path = WWW_PATH.'/upload/'; // 原路径
$dest_path = WWW_PATH.'/supload/'; // 目标路径
$path = isset($_GET['path'])? $_GET['path'] : ''; // 访问的图片URL
// 检查path
if(!$path){
exit();
}
// 获取图片URI
$relative_url = str_replace($dest_path, '', WWW_PATH.$path);
// 获取type
$type = substr($relative_url, 0, strpos($relative_url, '/'));
// 获取config
$config = isset($thumb_config[$type])? $thumb_config[$type] : '';
// 检查config
if(!$config || !isset($config['fromdir'])){
exit();
}
// 原图文件
$source = str_replace('/'.$type.'/', '/'.$config['fromdir'].'/', $source_path.$relative_url);
// 目标文件
$dest = $dest_path.$relative_url;
// 创建缩略图
$obj = new PicThumb($logfile);
$obj->set_config($config);
if($obj->create_thumb($source, $dest)){
ob_clean();
header('content-type:'.mime_content_type($dest));
exit(file_get_contents($dest));
}
?>
ThumbConfig.php 配置参数如下:
<?php
$thumb_config = array(
'news' => array(
'fromdir' => 'news', // 来源目录
'type' => 'fit',
'width' => 100,
'height' => 100,
'bgcolor' => '#FF0000'
),
'news_1' => array(
'fromdir' => 'news',
'type' => 'fit',
'width' => 200,
'height' => 200,
'bgcolor' => '#FFFF00'
),
'article' => array(
'fromdir' => 'article',
'type' => 'crop',
'width' => 250,
'height' => 250,
'watermark' => WWW_PATH.'/supload/watermark.png'
)
);
?>
访问以下路径时,系统将依据config配置自动生成对应的缩略图: http://localhost/supload/news/2013/07/21/1.jpg http://localhost/supload/news_1/2013/07/21/1.jpg http://localhost/supload/article/2013/07/21/2.jpg
本文所述实例的完整代码可通过点击此处本站下载获取。
希望本文所述的PHP程序设计技巧能对各位读者有所帮助。