首页 >PHP >Nginx使用图片处理模块的方法实例

Nginx使用图片处理模块的方法实例

  • PHP2396
  • 2018-03-06 17:34:36

Nginx可以编写很多额外的模块,这里我们需要按照能够通过URL响应返回缩放且含图片水印功能的模块。

1.安装一些使用过程中会用到的工具

yum install libgd2-devel
yum install libpcre-devel
yum install libcurl-devel
yum install gd-devel

2.安装Nginx,不知道怎么安装的可以参考这里 https://www.linuxidc.com/Linux/2018-03/151202.htm

3.下载模块源代码,将下载来的文件解压至Nginx的根目录

wget https://github.com/3078825/nginx-image/archive/master.zip
cd /usr/local/nginx-1.12.2/
unzip master.zip

4.配置Nginx的参数,添加图片处理模块

./configure --add-module=ngx_image_thumb-master

5.编译安装

make && make install

6.配置nginx.conf文件

location ~*\.(jpg|png|gif){
    root /home/upload/nginx/;
    image on;
    #image_backend off;
    image_output on;
    #image_jpeg_quality 75;
    image_water on;
    image_water_type 0;
    image_water_pos 9;
    image_water_file "/home/upload/nginx/logo.png";
    #image_water_transparent 80;
}

7.配置参数说明

image on/off 
#是否开启缩略图功能,默认关闭
image_backend on/off 
#是否开启镜像服务,当开启该功能时,请求目录不存在的图片(判断原图),将自动从镜像服务器地址下载原图
image_backend_server 
#镜像服务器地址
image_output on/off 
#是否不生成图片而直接处理后输出 默认off
image_jpeg_quality 75 
#生成JPEG图片的质量 默认值75
image_water on/off 
#是否开启水印功能
image_water_type 0/1 
#水印类型 0:图片水印 1:文字水印
image_water_min 300 300 
#图片宽度 300 高度 300 的情况才添加水印
image_water_pos 0-9 
#水印位置 默认值9 0为随机位置,1为顶端居左,2为顶端居中,3为顶端居右,4为中部居左,5为中部居中,6为中部居右,7为底端居左,8为底端居中,9为底端居右
image_water_file "/home/upload/nginx/logo.png"
#水印文件(jpg/png/gif),绝对路径或者相对路径的水印图片
image_water_transparent 20
#水印透明度,默认20
image_water_text "Power By Vampire"
#水印文字 "Power By Vampire"
image_water_font_size 5
#水印大小 默认 5
image_water_font 
#文字水印字体文件路径
image_water_color #000000
#水印文字颜色,默认 #000000

8.调用说明

这里假设你的nginx访问地址为http://127.0.0.1/
并在nginx网站根目录存在一个test.jpg的图片
通过访问http://127.0.0.1/test.jpg!c300x200.jpg 将会生成/输出test.jpg 300x200 的缩略图
其中c是生成图片缩略图的参数,300是生成缩略图的宽度,200是生成缩略图的高度
一共可以生成四种不同类型的缩略图。
支持 jpeg/png/gif(Gif生成后变成静态图片)

C 参数按请求宽高比例从图片高度 10% 处开始截取图片,然后缩放/放大到指定尺寸(图片缩略图大小等于请求的宽高)
M 参数按请求宽高比例居中截图图片,然后缩放/放大到指定尺寸(图片缩略图大小等于请求的宽高)
T 参数按请求宽高比例按比例缩放/放大到指定尺寸(图片缩略图大小可能小于请求的宽高)
W 参数按请求宽高比例缩放/放大到指定尺寸,空白处填充白色背景颜色(图片缩略图大小等于请求的宽高)