WebP是Google在2010年提出的一种新的图像格式。对于包含大量图片的网站,大多会使用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';
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、jpeg、png的格式。
4 天前