本博客列表縮略圖在支持webp格式的瀏覽器下,使用的是webp格式圖片,不支持webp圖片下使用的是原圖片(如png,gif,jpg等)
webp使用指南,請參考 https://www.imqianduan.com/browser/webp.html
如何轉換webp?
google官方有推出工具cwebp用來轉換webp,可以通過命令行的形式使用webp
cwebp官方文檔: https://developers.google.com/speed/webp/download
這里我們使用另一個基於cwebp封裝后的插件 web-converter,使用起來相對比較簡單
安裝webp-converter及使用
// 安裝npm install webp-converter --save
// 使用var webp=require('webp-converter');//pass input image(.jpeg,.pnp .....) path ,output image(give path where to save and image file name with .webp extension)//pass option(read documentation for options)//cwebp(input,output,option,result_callback)webp.cwebp("input.jpg","output.webp","-q 80",function(status,error){//if conversion successful status will be '100'//if conversion fails status will be '101'console.log(status,error);});
問題
webp-converter在本地(windows 7)安裝測試一點問題沒有,傳至服務器就報錯了
錯誤:
cwebp: error while loading shared libraries: libaio.so.6: cannot open shared object file: no such file or directory
一直以為是路徑問題,后來發現是依賴包的問題,
解決:
安裝linux缺失依賴,問題解決
yum install libXext.x86_64yum install libXrender.x86_64yum install libXtst.x86_64
瀏覽器判斷是否支持webp
通過http請求的accept字段,可以判斷瀏覽器是否支持webp格式
本博客使用的是eggjs框架:
// 是否支持webpconst requestAccept = ctx.request.headers.accept;const isSuportWebP = /image\/webp/gi.test(requestAccept);
eggjs使用Nunjucks作為模板,在模板中判斷isSuportWebP是否為true,是則輸出webp格式的URL,否則輸出默認圖片格式URL
