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

这篇文章主要介绍了使用nginx动态转换图片大小生成缩略图,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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动态转换图片大小内容请搜索安全小天地以前的文章或继续浏览下面的相关文章希望大家以后多多支持安全小天地!

------本文已结束,感谢您的阅读------
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
善语结善缘,恶语伤人心
提交
头像

昵称

取消
昵称常用语 夸夸
夸夸
还有吗!没看够!
表情图片

    暂无评论内容