thinkphp5动态缩略图实现_tp5 缩略图
1、动态缩略图程序
由于tp5自带图片处理类,我们就可以不用再另外写裁剪等方法了,但是tp5的图片处理类没有输出方法,我们复制一份save的方法,另外命名一个preview的方法,稍微修改下用来输出就行了。(此类文件路劲在vendor/topthink/think-image/src/Image.php,如果没有这个类文件请用composer下载。)代码如下:
`public function preview($quality = 100, $interlace = true)
{
$type = $this->info['type'];
header('content-type:'.$this->info['mime']);
if ('jpeg' == $type || 'jpg' == $type) {
//JPEG图像设置隔行扫描
imageinterlace($this->im, $interlace);
imagejpeg($this->im, null, $quality);
} elseif ('gif' == $type && !empty($this->gif)) {
imagegif($this->im, null);
} elseif ('png' == $type) {
//设定保存完整的 alpha 通道信息
imagesavealpha($this->im, true);
//ImagePNG生成图像的质量范围从0到9的
imagepng($this->im, null, min((int) ($quality / 10), 9));
} else {
$fun = 'image' . $type;
$fun($this->im, '');
}
exit; //一定要写exit,不然输出的是二进制代码
}`
我们随意创建一个控制器和一个方法,例如:Image/thumb,调用刚刚我们修改的方法,代码如下:
`public function thumb($path,$width=160,$height=120)
{
$image = thinkImage::open(trim($path,'/'));
$image->thumb($width,$height)->preview();
}`
假设我们在根目录有个图片test.jpg
访问路径:http://thinkphp5/Image/thumb?path=test.jpg&width=320&height=240
这个时候我们会看到一个新的缩略图了,下面就要开始配置服务端了。
2、配置服务端
我们之前已经有过thinkphp隐藏index.php的配置了,这样加我们新的配置上去就可以了。
apache的配置
`<IfModule mod_rewrite.c>
Options +FollowSymlinks -Multiviews
RewriteEngine On
#新增配置
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+.(jpg|jpeg|png|gif))!(d+)x(d+).*$ image/thumb?path=$1&width=$3&height=$4
#新增配置
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php/$1 [QSA,PT,L]
</IfModule>`
nginx的配置
`if (!-e $request_filename) {
#新增配置
rewrite ^(.+.(jpg|jpeg|png|gif))!(d+)x(d+).*$ image/thumb?path=$1&width=$3&height=$4;
#新增配置
rewrite ^(.*)$ /index.php?s=$1 last;
break;
}`
访问根目录的test.jpg图片,路径:http://thinkphp5/test.jpg!320x240
到这里就大功告成了!
License:
CC BY 4.0