网页以webp方式显示,提高加载速度

代码归类 Views
网页以webp方式显示,是谷歌倡导的一种新的图片格式,以压缩图片大小 提高网页加载速度
//判断浏览器是否支持webp
 var isSupportWebp = !![].map && document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0;
//console.log(isSupportWebp);   // true or false

//webp图片互转
转webp需要借助官方dll(NoesisWebP.dll)
//Load a WebP image
using (Bitmap image = WebPFormat.LoadFromStream(new FileStream("image.webp", FileMode.Open, FileAccess.Read)))
{
    image.Save("image.png", ImageFormat.Png);
}
//Save a WebP image
using (Image image = Image.FromFile("image.jpg"))
{
    Bitmap bitmap = new Bitmap(image);
    WebPFormat.SaveToFile("image.webp", bitmap);
}

//webp图片展示
function checkWebp(callback) {
  var img = new Image();
  img.onload = function () {
    var result = (img.width > 0) && (img.height > 0);
    callback(result);
  };
  img.onerror = function () {
    callback(false);
  };
  img.src = 'data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA';
}


function showImage(useWebp){
  var imgs = Array.from(document.querySelectorAll('img'));

  imgs.forEach(function(i){
    var src = i.attributes['data-src'].value;

    if (useWebp){
      src = src.replace(/\.jpg$/, '.webp');
    }

    i.src = src;
  });
}

checkWebp(showImage);
评论 --
  • 消灭零回复