可以考虑使用 Linux 自带的图像处理工具 ImageMagick
以下是基于 ImageMagick 的示例代码:
#!/bin/bash
# 指定缓存路径和压缩比例
cache_path="/path/to/cache"
quality=80
# 循环处理缓存目录下的所有图片文件
for file in $cache_path/*.jpg; do
# 使用 ImageMagick 进行压缩,将压缩后的文件覆盖原始文件
convert "$file" -quality $quality "$file"
done
在这个脚本中,我们指定了缓存路径和压缩比例,并使用 ImageMagick 的 convert 命令压缩缓存目录下的所有 JPG 格式图片。通过调整 quality 参数的值可以控制压缩比例,从而达到不同的压缩效果和文件大小。
使用脚本批量压缩图片可能会对服务器性能产生一定的影响,特别是当缓存的图片数量较大时。因此,建议在服务器空闲时运行该脚本,以避免影响其他正在运行的服务。
可以将上面的脚本嵌入到 Nginx 的配置文件中,使用 Nginx 的 nginx.conf 文件中的 init_by_lua_block 指令执行 Lua 脚本来调用该脚本。
示例代码:
http {
# 定义变量
set $cache_path "/path/to/cache";
set $quality "80";
# 使用 init_by_lua_block 调用脚本
init_by_lua_block {
-- 定义脚本
local cmd = "/bin/bash -c '/path/to/script.sh " .. ngx.var.cache_path .. " " .. ngx.var.quality .. "'";
os.execute(cmd);
}
# 添加反向代理配置,缓存并压缩图片
server {
listen 80;
server_name example.com;
location / {
add_header Cache-Control "public";
proxy_pass http://backend_server$request_uri;
proxy_set_header Host $http_host;
proxy_cache my_cache;
# 使用 image_filter 压缩图片
image_filter resize 800 -1;
image_filter_jpeg_quality $quality;
}
# 设置缓存路径
location /cache/ {
internal;
alias $cache_path/;
}
}
}
在这个配置中,我们首先定义了 $cache_path 和 $quality 两个变量,并在 init_by_lua_block 中执行调用 /path/to/script.sh 脚本,其中 $cache_path 和 $quality 作为参数传递给脚本。脚本的执行结果是对缓存目录下的 JPG 图片进行压缩。
接下来,我们添加了反向代理配置,使用 image_filter 来压缩图片。image_filter 是 Nginx 内置的图像处理模块,可以用于实时处理图像文件。在这个配置中,我们在缓存中引用图片时,将图片请求转发到名为 /cache/ 的内部位置上,并使用 image_filter 对图片进行实时压缩。
- All rights reserved.
- No part of this website, including text and images, may be reproduced, modified, distributed, or transmitted in any form or by any means, without the prior written permission of the author.
- Unauthorized commercial use is strictly prohibited.
- Unauthorized personal use is strictly prohibited.