nodejs應用轉換png,jpg,gif為webp圖片格式


本博客列表縮略圖在支持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及使用

  1. // 安裝
  2. npm install webp-converter --save
  1. // 使用
  2. var webp=require('webp-converter');
  3. //pass input image(.jpeg,.pnp .....) path ,output image(give path where to save and image file name with .webp extension)
  4. //pass option(read documentation for options)
  5. //cwebp(input,output,option,result_callback)
  6. webp.cwebp("input.jpg","output.webp","-q 80",function(status,error){
  7. //if conversion successful status will be '100'
  8. //if conversion fails status will be '101'
  9. console.log(status,error);
  10. });

問題

webp-converter在本地(windows 7)安裝測試一點問題沒有,傳至服務器就報錯了

錯誤:

  1. cwebp: error while loading shared libraries: libaio.so.6: cannot open shared object file: no such file or directory

一直以為是路徑問題,后來發現是依賴包的問題,
解決:
安裝linux缺失依賴,問題解決

  1. yum install libXext.x86_64
  2. yum install libXrender.x86_64
  3. yum install libXtst.x86_64

瀏覽器判斷是否支持webp

通過http請求的accept字段,可以判斷瀏覽器是否支持webp格式

本博客使用的是eggjs框架:

  1. // 是否支持webp
  2. const requestAccept = ctx.request.headers.accept;
  3. const isSuportWebP = /image\/webp/gi.test(requestAccept);

eggjs使用Nunjucks作為模板,在模板中判斷isSuportWebP是否為true,是則輸出webp格式的URL,否則輸出默認圖片格式URL


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM