您当前的位置:首页 > 网站建设 > 网站维护
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery |

使用nginx动态转换图片大小生成缩略图

51自学网 2022-07-04 11:34:20
  网站维护

Nginx的ngx_http_image_filter_module 模块(nginx版本为0.7.54+) 可用来动态转换JPEG, GIF, PNG, 和WebP格式的图片大小。

该模块默认没有构建,需要通过 --with-http_image_filter_module 配置参数启用。

如果图片访问量不大,可以使用该模块。

该模块使用了libgd库。 推荐使用该库的最新版本。

以下为在已经安装了nginx的情况下添加该模块的步骤。

1 安装依赖

yum -y install gd-develyum -y install libxslt-develyum -y install perl-devel perl-ExtUtils-Embed

2 查看原nginx参数

​ nginx -V

输出结果如下:

​ nginx version: nginx/1.12.2
​ configure arguments:

查看是否有--with-http_image_filter_module,如果有则说明已经安装过,否则继续安装。

3 编译

重新编译时需要下载和原来相同版本的nginx源码,解压。

添加--with-http_image_filter_module=dynamic及原来的参数(不需要执行make install命令重新安装)

./configure --with-http_image_filter_module=dynamicmake

4 备份原nginx

cp -r /usr/local/nginx /usr/local/nginxbak

5 覆盖nginx

cp objs/nginx /usr/local/nginx/sbin/mkdir /usr/local/nginx/modulecp objs/ngx_http_image_filter_module.so /usr/local/nginx/module/ngx_http_image_filter_module.so

6 修改配置文件

vim /usr/local/nginx/conf/nginx.conf

load_module /usr/local/nginx/module/ngx_http_image_filter_module.so;location ~* /images/(.+)_(/d+)x(/d+)/.(jpg|jpeg|gif|png)$ {        set $w $2;        set $h $3;        image_filter resize $w $h;        image_filter_buffer 30M; #设置图片缓冲区的最大大小,大小超过设定值,服务器将返回错误415        image_filter_interlace on;        image_filter_jpeg_quality 80;        try_files /$1.$4 /notfound.jpg;        expires 1d;        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Credentials' 'true';        alias /home/publisherupload/ ; #root 能够让访问 /images/ 路径时,访问到 /User/XX/Desktop/images,如果将 root 替换为 alias,则访问的是 /User/XX/Desktop/;其中 /User/XX/Desktop/ 是本机中的绝对路径。    }location /images {  alias /home/publisherupload/ ; #root 能够让访问 /images/ 路径时,访问到 /User/XX/Desktop/images,如果将 root 替换为 alias,则访问的是 /User/XX/Desktop/;其中 /User/XX/Desktop/ 是本机中的绝对路径。  autoindex on; #打开目录浏览功能}

7 重载nginx配置

/usr/local/nginx/sbin/nginx -s

8 测试

最终的图片访问地址为在原图片地址后面加入_宽度X高度参数

http://110.87.103.58:12345/images/2021-01/202101250944272_500x400.png

参考

https://cloud.tencent.com/developer/article/1644466


下载地址:
Nginx+Tomcat实现负载均衡、动静分离的原理解析
Tomcat配置及如何在Eclipse中启动
51自学网,即我要自学网,自学EXCEL、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。
京ICP备13026421号-1