Canvas对ImageData进行Resize操作(平滑高性能处理)

问题背景

通过getImageData函数得到的ImageData通过putImageData重新放到canvas容器无法进行resize操作,如果通过toDataURL函数转为Image再使用drawImage函数性能太差。

解决代码

处理代码出自:https://gist.github.com/mauriciomassaia/b9e7ef6667a622b104c00249f77f8c03

// 输入imageData,resize后的长宽
async function resizeImageData(imageData, width, height) {
				const resizeWidth = width >> 0
				const resizeHeight = height >> 0
				const ibm = await window.createImageBitmap(imageData, 0, 0, imageData.width, imageData.height, {
					resizeWidth,
					resizeHeight
				})
				const canvas = document.createElement('canvas')
				canvas.width = resizeWidth
				canvas.height = resizeHeight
				const ctx = canvas.getContext('2d', {
					willReadFrequently: true
				})
				// 不注释这一行, 得到的图像就会有缺失
				// ctx.scale(resizeWidth / imageData.width, resizeHeight / imageData.height)
				ctx.drawImage(ibm, 0, 0)
				return ctx.getImageData(0, 0, resizeWidth, resizeHeight)
}

上述代码是目前性能与表现最好的方案。

调用代码

const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d', { willReadFrequently: true })
// 返回的结果是一个Promise
resizeImageData(imgData, resizeWidth, resizeHeight).then(data => {
	// 后面两位0, 0代表图像起始点的左上角
	ctx.putImageData(data, 0, 0)
});

其他优化

使用willReadFrequently,在频繁使用getImageData的情况下可以进行提速。

MDN原文:A boolean value that indicates whether or not a lot of read-back operations are planned. This will force the use of a software (instead of hardware accelerated) 2D canvas and can save memory when calling getImageData() frequently.

const ctx = canvas.getContext('2d', { willReadFrequently: true })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alex-Leung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值