利用canvas将其他图片格式转为webp
webp这种格式的主要优势在于高效率。在质量相同的情况下,WebP格式图像的体积要比JPEG格式图像小40%。图片上传时,可以利用canvas将其他图片格式转为webp,这样可以大幅减少图片体积。这样加载图片就可以更快,提高页面性能。经过测试jpg,jpeg,png,bmp,这些格式的图片都是可以利用下面方法进行转换达到压缩体积。
getWebpFileByImageFil(imageFile): Promise<any> {
const _this = this
return new Promise((resolve, reject) => {
const imageFileReader = new FileReader()
imageFileReader.onload = function (e) {
const image = new Image()
image.src = e.target.result as string
image.onload = function () {
const canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
canvas.getContext('2d').drawImage(image, 0, 0)
resolve(_this.base64ToFile(canvas.toDataURL('image/webp'), imageFile.name))
}
}
imageFileReader.readAsDataURL(imageFile)
})
}
}
转换后的图片体积有效减少。
利用canvas将页面进行截图
利用到一个库html2canvas,该库可以将dom元素copy生成对应的canvas,在利用canvas转化为webp或者其他格式的图片。
import html2canvas from "html2canvas"
const convertToImage = (dom, options = {}) => {
// html2canvas配置项
const ops = {
useCORS: true,
allowTaint: false,
...options
}
return html2canvas(dom, ops).then(canvas => {
// 返回图片的二进制数据
return canvas.toDataURL('image/webp', 0.5)
})
}