基于 URL 的缩略图在 Laravel 中的实现
导语#
网站开发常会遇到缩略图的问题,一个文章可能会有几种大小的缩略图,一般会在上传图片的时候后台代码自动生成几种缩略图,这种方式就需要一次生成很多图片,今天介绍一种基于 URL 动态生成缩略图的方式,大家可以沿着这个方向去探索基于 URL 的图片处理等。
先来看看啥叫基于URL动态生成缩略图。
/resize/<strong>400x200</strong>/images/thumb/e8ad3e43e64462c80e7f43fc51f7f948.jpg>400x200/images/thumb/e8ad3e43e64462c80e7f43fc51f7f948.jpg
我们改变上述链接中的400x200得到一个400x200的图片,改变为100x100得到一个100x100大小的图片,这个就是基于URL动态生成缩略图,后台只要保存一张原图即可。
下面就说下如何使用此方式:
1. 安装 intervention/image 和 intervention/imagecache 包。
composer require intervention/image
composer require intervention/imagecache
2. 发布报配置。在 config 文件夹下找到 imagecache.php
<?php
return array(
'route' => 'resize',
'paths' => array(
public_path('upload'),
public_path('images')
),
'templates' => array(
'400x200' => 'App\Filters\MyFilter'
),
'lifetime' => 43200,
);
3. 配置 imagecache.php 文件中的
'route' => 'resize'
4. 定义资源文件夹
'paths' => array( 'storage/uploads/images', public_path('img') )
5. 修改
'templates' => array('400x200' => 'App\Filters\MyFilter'),
6. 定义 App\Filters\MyFilter
<?php
namespace App\Filters;
use Intervention\Image\Image;
use Intervention\Image\Filters\FilterInterface;
class MyFilter implements FilterInterface {
public function applyFilter(Image $image) {
return $image->fit(400, 200);
}
}
7. 配置 Lifetime
'lifetime' => 43200
现在就可以通过上述的 url 访问到自定义的缩略图了
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: