转载:http://houxiyang.com/archives/112/
- 面临的问题
网站需求变更,需要更多不同尺寸的缩略图
有些图片的缩略图很少使用到,但还是存在了硬盘上,造成空间浪费
- 解决方法
Nginx搭配Lua模块,如果访问的图片不存在,则调用GraphicsMagick的命令行实时生成指定尺寸的图片。
-集成了Lua模块的Nginx项目OpenResty
-GraphicsMagick的安装和使用
-具体使用方法
原始图片地址:
/images/f47aa98b47b4b7bd.jpg
自定义图片尺寸:
/images/f47aa98b47b4b7bd_40x40.jpg
配置文件中可以写成这样
location ~ '/images/([0-9a-z]+)_([0-9]+)x([0-9]+).jpg$' {
root /home/images;
set $image_root = '/home/images';
set $fileName = ngx.arg[1];
set $width = ngx.arg[2];
set $height = ngx.arg[3];
set $origin = $image_root/$fileName.jpg
set $file = $image_root/$fileName_$widthx$height.jpg
if (!-f $file) {
rewrite_by_lua '
local command = "gm convert "..ngx.var.origin.." -thumbnail "..ngx.var.width.."x"
..ngx.var.height.." "..ngx.var.file;
os.execute(command);
';
}
这样就能简单的生成图片指定尺寸的缩略图了。
摘自:http://blog.csdn.net/vboy1010/article/details/7868645
安装lua模块
1、Luajit2.0(推荐)或者 Lua5.1(Lua5.2暂不支持)
- wget http://luajit.org/download/LuaJIT-2.0.0-beta9.tar.gz
- tar zxvf LuaJIT-2.0.0-beta9.tar.gz
- cd LuaJIT-2.0.0-beta9
- make
- sudo make install PREFIX=/usr/local/luajit
Note: to avoid overwriting a previous version,
the beta test releases only install the LuaJIT executable under the versioned name (i.e. luajit-2.0.0-beta10).
You probably want to create a symlink for convenience, with a command like this:
sudo ln -sf luajit-2.0.0-beta9 /usr/local/bin/luajit (加上这句命令)
下面需要配置一下 luajit 或 lua 的环境变量(Nginx编译时需要):
- -- luajit --
- # tell nginx's build system where to find LuaJIT:
- export LUAJIT_LIB=/path/to/luajit/lib
- export LUAJIT_INC=/path/to/luajit/include/luajit-2.0
- -- lua --
- # or tell where to find Lua if using Lua instead:
- export LUA_LIB=/path/to/lua/lib
- export LUA_INC=/path/to/lua/include
我的测试环境里,配置如下:
- export LUAJIT_LIB=/usr/local/luajit/lib
- export LUAJIT_INC=/usr/local/luajit/include/luajit-2.0