转载:https://segmentfault.com/a/1190000005898538?utm_source=tuicool&utm_medium=referraljavascript
webp是一种同时提供了有损压缩与无损压缩的图片档案格式 ,衍生自影像编码格式VP8,是由Google在购买On2 Technologies后发展出来,以BSD受权条款释出。根据 Google 的测试,无损压缩后的 WebP 比 PNG 文件少了 45% 的文件大小,即便这些 PNG 文件通过其余压缩工具压缩以后,WebP 仍是能够减小 28% 的文件大小。WebP最初在2010年释出,目标是减小档案大小,但达到和JPEG格式相同的图片品质,但愿可以减小图片档在网路上的传送时间。html
WebP使用VP8做为压缩演算法java
如下为CAN I USE 的数据,绿色为支持的浏览器android
同质量的前提下,WebP体积大约只有JPEG的1/3,对于采用大量图片的网页,WebP格式能够节省大量带宽,大幅提高网页加载速度。例如,YouTube的视频略缩图采用WebP格式后,网页加载速度提高了10%;谷歌的Chrome 网上应用商店采用WebP格式图片后,天天能够节省几TB的带宽,页面平均加载时间大约减小1/3;Google+移动应用采用WebP图片格式后,天天节省了50TB数据存储空间。github
对于图片占主要流量的网站,使用webp格式图片能很大程度减少图片体积,在我以前的一个项目里,首页是四张大图的轮播,图片优化很成问题,在使用webp格式图片后,图片体积减少了70%以上,目测图片质量没有影响web
方法一:算法
function checkWebp() { try{ return (document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0); }catch(err) { return false; } } console.log(checkWebp()); // true or false
方法是在其余地方上看到的,我用trycatch改写了一下canvas
原理:segmentfault
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.
方法二:
var d = document; var check = function() { var supportWebp; try { var ele = d.createElement('object'); ele.type = 'image/webp'; ele.innerHTML = '!'; d.body.appendChild(ele); //奇妙所在,若是浏览器支持webp,那么这个object是不可见的(offsetWidth为0), //不然就会显示出来,有可视宽度. supportWebp = !ele.offsetWidth; d.body.removeChild(ele); }catch (err) { supportWebp = false; } return supportWebp; }
此方法是在看某个项目的源码时看到的
1.若使用场景是浏览器,能够:
JavaScript 能力检测,对支持 WebP 的用户输出 WebP 图片
使用 WebP 支持插件:WebPJS
2.若使用场景是 App,能够:
Android 4.0 如下 WebP 解析库(连接)
iOS WebP 解析库(连接)