前端WebP图片的使用,以及转换WebP格式

更新日期: 2023-09-15阅读: 753标签: webp

WebP是Google在2010年提出的一种新的图像格式。对于包含大量图片的网站,大多会使用WebP格式的图片,这样不仅可以减少流量带宽,还可以减少用户访问的加载时间,提高用户体验。 目前,WebP已经成为主流网站青睐的图像格式。


在网页中运用 WebP

既然WebP这么好用,那么如何在网页中使用WebP图片呢? 这其实很简单。 我们可以通过html代码在网页中使用WebP格式的图片。

<picture>
  <source srcset="image.webp" type="image/webp">
  <source srcset="image.jpg" type="image/jpeg">
  <img src="image.jpg" alt="image">
</picture>

在上面的代码中,<picture> 元素包含了两个 <source> 元素和一个 <img> 元素。<source> 元素用于指定不同格式的图片,<img> 元素则是在所有格式的图片都无法显示时显示的默认图片。替换:对于不支持 WebP 格式的浏览器,可以使用 JavaScript 进行检测和替换。

var img = new Image();
img.onload = function() {
  if (img.width > 0 && img.height > 0) {
    document.getElementById('my-img').src = 'image.webp';
  }
}
img.onerror = function() {
  document.getElementById('my-img').src = 'image.jpg';
}
img.src = 'image.webp';


Js实现图片转WebP格式

Javascript 利用canvas可以直接将 jpeg、png 转换为 webp,示例代码如下:

/**
* 根据 jpeg、png File 文件对象,获取 webp 格式的 File 文件对象
* @param {File} imageFile jpeg、png图片文件对象
* @returns image/webp File
*/
const getWebpFileByImageFile = imageFile => {
const base64ToFile = (base64, fileName) => {
let arr = base64.split(','),
type = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], fileName, {
type
});
};
return new Promise((resolve, reject) => {
const imageFileReader = new FileReader();
imageFileReader.onload = function(e) {
const image = new Image();
image.src = e.target.result;
image.onload = function() {
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext("2d").drawImage(image, 0, 0);
resolve(base64ToFile(canvas.toDataURL("image/webp"), imageFile.name.split(".")[0] + ".webp"))
}
}
imageFileReader.readAsDataURL(imageFile)
});
}


在线工具转换WebP格式

该工具目前仅支持转换为webp、jpeg、png的格式。

地址入口:https://www.fly63.com/tool/imgformat/


链接: https://www.fly63.com/article/detial/12516

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!