图片优化 - 转webp

5,279 阅读3分钟

一、什么是webp

webp 是由谷歌(google)开发的一种旨在加快图片加载速度的图片格式。与JPEG相同,WebP是一种有损压缩利用预测编码技术。但谷歌表示,这种格式的主要优势在于高效率。在质量相同的情况下,WebP格式图像的体积要比JPEG格式图像小40%,webp 在各大BAT公司得到广泛的运用,如淘宝、腾讯等。

并且阿里云、腾讯云、又拍云都提供了图片直接转换webp的相关服务。以阿里云为例,只要在图片后缀加上 ?x-oss-process=image/format,webp 你的图片瞬间会变小很多:

云服务 普通图片 WEBP图片
阿里云 image-demo.oss-cn-hangzhou.aliyuncs.com/panda.png (18K) image-demo.oss-cn-hangzhou.aliyuncs.com/panda.png?x… (3.3K)

阿里云支持GIF转webp啦,体积减小 20% ~ 60%

二、实现webp

该方法可作为底层方法直接使用,代码如下:

/**
 * 检查是否支持.webp 格式图片  使用阿里CDN
 *
 * 支持 webp     ?x-oss-process=image/format,webp
 * 不支持         ?x-oss-process=image/quality,Q_80    质量变更为80%  GIF不作此处理
 */

;
(function() {
  var urlarr = [];
  // localStorage存在且之前没设置过iswebp
  if (localStorage && !localStorage.iswebp) {
    var cs = document.createElement('canvas');

    // 如果不支持canvas则退出
    if (cs.getContext && cs.getContext('2d')) {
      try {
        localStorage.iswebp = (0 === cs.toDataURL('image/webp').indexOf('data:image/webp'));
      } catch (e) {
        // safari 浏览器无恒模式在低于11版本会有bug
        // https://stackoverflow.com/questions/21159301/quotaexceedederror-dom-exception-22-an-attempt-was-made-to-add-something-to-st
        console.error(e);
      }
    }
  }

  function getOssImg(url) {
    if (!url) {
      return url;
    }
    if(Object.prototype.toString.call(url) !== '[object String]'){
      return url;
    }

    // 是否gif判断
    let isGif = false;
    urlarr = url.split('.');
    if (urlarr.length > 0 && urlarr[urlarr.length - 1] === 'gif') {
      isGif = true;
    }
    // gif已经支持webp
    if (isGif) {
      if (localStorage && localStorage.iswebp) {
        url = url + '?x-oss-process=image/format,webp';
        return url;
      } else {
        url += '';
        return url;
      }
    }
    
    // 不支持localStorage或者没有设置过iswebp或者isweb是false
    if (!localStorage || !localStorage.iswebp || localStorage.iswebp === 'false') {
      url = url + '?x-oss-process=image/quality,Q_80';
      return url;
    } else {
      url = url + '?x-oss-process=image/format,webp';
      return url;
    }
  }

  String.prototype.ossimg = function() {
    return getOssImg(this);
  };
})();

调用方式.ossimg() 如:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>checkwebp</title>
  </head>
  <body>
    <div class="J_checkImg"><img src="http://yun.tuidove.com/mami-media/img/ckey3d2q6o.png"></div>
    <script src="http://nansenzsl.coding.me/CBS/zepto.js"></script>
    <script src="http://nansenzsl.coding.me/CBS/checkwebp.js"></script>
    <script>
      $(function() {
        var $img = $('.J_checkImg img');
        $img.attr('src', $img.attr('src').ossimg()); // .ossimg() 转成webp
      });
    </script>
  </body>
</html>

三、兼容性

image
从兼容图表可以看出,在Chrome和Opera中兼容webp,但在IE、FF、Safari不兼容webp。Android和IOS表现也相差很大,Android基本兼容webp,iOS则都不兼容,在以上底层代码中考虑到了这一点。

webp的坑点分析(左边是jpg 右边是webp)

image

转为webp格式后,体积增加了近一倍,这是为什么呢?

① Type变更:原图的Type为Palette,处理之后的Type为TrueColor,即原图为索引类型,处理之后的图片为RGB真彩色,需要编码的像素点个数是索引类型的三倍,因此导致图片变大

② Colors变多:颜色数目由256增长到了67000多个,说明处理前的图片细节上重复较多,导致了处理后的图片比原图还大了很多

所以使用webp的时候需要注意,当图片有渐变和外发光并且通过tinypng压缩,再转webp格式,图片就会变大。

四、总结

webp能使全站图片缩小30%左右,这不得不说是一个很大的优化,还未使用webp的同学可以用起来。