让浏览器支持Webp

Webp介绍

webp是一种同时提供了有损压缩与无损压缩的图片档案格式 ,衍生自影像编码格式VP8,是由Google在购买On2 Technologies后发展出来,以BSD授权条款释出。根据 Google 的测试,无损压缩后的 WebP 比 PNG 文件少了 45% 的文件大小,即使这些 PNG 文件经过其他压缩工具压缩之后,WebP 还是可以减少 28% 的文件大小。 
WebP最初在2010年释出,目标是减少档案大小,但达到和JPEG格式相同的图片品质,希望能够减少图片档在网路上的传送时间。

技术

WebP使用VP8作为压缩演算法

支持

以下为CAN I USE 的数据绿色为支持的浏览器

转换工具

智图 
isparta

使用场景

当对图片大小的要求不同 
)

当对图片质量要求不同 
)

判断浏览器支持webp的方法

方法一:

  1. function checkWebp() {
  2. try{
  3. return(document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0);
  4. }catch(err) {
  5. return false;
  6. }
  7. }
  8. console.log(checkWebp()); // true or false


原理:

The HTMLCanvasElement.toDataURL() method returns a data URI containing a representation of the image in the format specified by the type parameter (defaults to PNG). The returned image is in a resolution of 96 dpi.

  • If the height or width of the canvas is 0, the string "data:," is returned.
  • If the requested type is not image/png, but the returned value starts with data:image/png, then the requested type is not supported.
  • Chrome also supports the image/webp type.

方法二:

  1. var d = document;
  2. var check = function() {
  3. var supportWebp;
  4. try {
  5. var ele = d.createElement('object');
  6. ele.type = 'image/webp';
  7. ele.innerHTML = '!';
  8. d.body.appendChild(ele);
  9. //奇妙所在,如果浏览器支持webp,那么这个object是不可见的(offsetWidth为0),
  10. //否则就会显示出来,有可视宽度.
  11. supportWebp = !ele.offsetWidth;
  12. d.body.removeChild(ele);
  13. }catch (err) {
  14. supportWebp = false;
  15. }
  16. return supportWebp;
  17. }


让浏览器支持webp

  1. 若使用场景是浏览器,可以: 
    JavaScript 能力检测,对支持 WebP 的用户输出 WebP 图片 
    使用 WebP 支持插件:WebPJS
  2. 若使用场景是 App,可以: 
    Android 4.0 以下 WebP 解析库(链接) 
    iOS WebP 解析库(链接
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值