banner
半米牙

半米牙的笔记

分享技术、记录生活
email

Nginx+Lua+libwebp 實現伺服器圖片自動轉WebP

服务器的流量和加載速度一直是優化的重點,既能保證圖片的清晰,又能節省流量、提高加載速度才是一個優秀網頁需要達到的目標。

Google 推出了一種圖片格式: WebP (Google 官方網址),比同類圖片壓縮率更高,相同畫質下,文件的體積更小 40%。而且主流瀏覽器的支持率已經達到 80%

查看支持率

ng1

原圖加載截圖:(12.61s)

ng2

WebP 加載截圖:(4.72s)

ng3

可以看出加載 Webp 會大大提高加載速度

Nginx 安裝 Lua 模塊#

服務器安裝 libwebp#

libwebp 是圖片轉成 webp 的工具

yum install libwebp-tools

測試:

cwebp -q 100 1.jpg -o 1.webp

ng4

如果出現以上信息,說明安裝成功。

nginx.conf#

配置:

.png.webp.jpg.webp.gif.webp的請求執行轉 WebP 的 lua 文件。

location /img {
    expires               365d;
    autoindex             on;
    autoindex_exact_size  on;
    try_files             $uri $uri/ @webp;
}
    
location @webp {    
    if ($uri ~ \.(png|jpg|gif)\.webp) {
        content_by_lua_file  lua/imgProcess.lua;
    }
}

ng5

imgProcess.lua#

function file_exists(name) --判斷文件是否存在的方法
    local f=io.open(name,"r");
    if f~=nil then io.close(f) return true else return false end
 end
 
 local newFile = ngx.var.request_filename;
 local originalFile = newFile:sub(1, #newFile - 5); --請求的webp圖片去掉.webp後綴

 if not file_exists(originalFile) then
   ngx.exit(404);
   return;
 end
 
 os.execute("cwebp -q 75 " .. originalFile  .. " -o " .. newFile);  --用libwebp轉換圖片

 if file_exists(newFile) then
     ngx.exec(ngx.var.uri); --重定向到轉換成的webp圖片
 else
     ngx.exit(404); --轉換失敗:404
 end

ng6

查看效果#

訪問前圖片,服務器上沒有 WebP 文件。

ng7

當服務器接收到.jpg.webp 的請求後,自動生成 WebP 文件:

ng8

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。