使用nginx image filter实现类OSS对象存储中对图片的实时处理
使用Nginx image_filter实现类似OSS图片处理 在家使用自己的电脑做了一个小应用,可查看照片,按以前的方式,需要在用户上传图片后对进行裁剪压缩,然后给前端一个缩略图地址与原图地址。这种方式有两个弊端磁盘空...
使用Nginx image_filter实现类似OSS图片处理
在家使用自己的电脑做了一个小应用,可查看照片,按以前的方式,需要在用户上传图片后对进行裁剪压缩,然后给前端一个缩略图地址与原图地址。这种方式有两个弊端磁盘空间的浪费、缩略图尺寸调整不便捷。是否有其他不使用云OSS存储的情况下自己实现一套类似OSS的图片处理?
后来搜索资料,发现使用nginx的image_filter可以实现。根据网上其他人的实例使用没有成功。
安装nginx与imageFilter不在复述,自己从网上看文章就可以了。我使用的版本是nginx 1.13.12 直接自带该插件。
自己调整后可以使用,下面贴出完整配置。
server {
listen 80;
server_name 127.0.0.1;
charset utf-8;
root /www/uploadfile;
#拦截所有带“!”号的图片请求
location ~* ^(.*\.(?:jpg|gif|png|jpeg|bmp))!(.*){
#rewrite ^(.*\.(?:jpg|gif|png))! $1;
#图片访问路径
set $filename $1;
#图片压缩尺寸
set $img_arg $2;
#拆解处理尺寸参数,参数性质如200x400样式
if ($img_arg ~ "^(\d+)x(\d+)") {
set $img_width $1;
set $img_height $2;
}
if ($img_arg ~ "^(\d+)$") {
set $img_width $1;
set $img_height "-";
}
if ($img_arg ~ "^x(\d+)") {
set $img_width "-";
set $img_height $1;
}
if ( $img_width = "" ){
set $img_width 100;
}
if ( $img_height = ""){
set $img_height 100;
}
#使用内部跳转,将尺寸参数传递
echo_exec /_imgFilt;
}
#图片处理
location /_imgFilt {
alias /www/uploadfile$filename;
image_filter resize $img_width $img_height;
image_filter_buffer 10M;
}
location ~ .*\.(swf|docx|doc|xls|xlsx|txt|pdf|ppt|pptx|mp3|zip|rar|tar|gz|mp4|ttf|ttc|fmap|fmi|theme)$ {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Headers' 'X-Requested-With';
add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
expires 30d;
}
}
图片访问请求地址: http://127.0.0.1/upload/20181120/1542720637600.jpg!500x400
使用以上请求,就可以实现使用nginx image filter实施图片处理。 因是自己的小应用在使用,所以性能与访问速度方面还可以。
非常耗费CPU资源,如果是公司业务,该方式请谨慎使用!!!
很赞哦! (1074)