zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    TCP/IP详解学习笔记
    python 中颜色的表示
    token工作原理
    sql注入相关链接记一次SQL注入实战
    python读写不同编码txt文件
    selenium+python 优化测试报告
    一个非常好的Linux学习网站
    jmeter 正则表达式 练习
    jmeter 实战项目总结2——微信端
    jmeter 实战项目总结1
  • 原文地址:https://www.cnblogs.com/zzsdream/p/11181374.html
Copyright © 2011-2022 走看看