本博客列表縮略圖在支持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_64
yum install libXrender.x86_64
yum install libXtst.x86_64
瀏覽器判斷是否支持webp
通過http
請求的accept
字段,可以判斷瀏覽器是否支持webp
格式
本博客使用的是eggjs
框架:
// 是否支持webp
const requestAccept = ctx.request.headers.accept;
const isSuportWebP = /image\/webp/gi.test(requestAccept);
eggjs
使用Nunjucks
作為模板,在模板中判斷isSuportWebP
是否為true
,是則輸出webp
格式的URL,否則輸出默認圖片格式URL