当前位置:   首页安装配置访问图片大小:使用nginx动态转换图片大小生成缩略图

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

发布日期:2021-04-29 15:32 | 文章来源:脚本之家

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-devel
yum -y install libxslt-devel
yum -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=dynamic
make

4 备份原nginx

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

5 覆盖nginx

cp objs/nginx /usr/local/nginx/sbin/
mkdir /usr/local/nginx/module
cp 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动态转换图片大小生成缩略图的文章就介绍到这了,更多相关nginx动态转换图片大小内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

联系我们
关于使用场景和技术架构的更多咨询,请联系我们的销售和技术支持团队。
Yingsoo Host

在线
客服

在线客服:7*24小时在线

客服
热线

400-630-3752
7*24小时客服服务热线

关注
微信

关注官方微信
顶部