利用blurhash技术,可以实现图片缩略图在网页上的预加载,而存储该缩略图,仅需要如下的一串简短的字符串。
LEHLk~WB2yk8pyo0adR*.7kCMdnj

BlurHash官网地址,可以在其中进行在线尝试。
注意到目前并没有相关的文章,故在此进行一个记录。
编码
1.首先安装相关插件,分别是blurhash相关与图片处理
npm i blurhash
npm i sharp
2. 然后导入相关的包与函数
const {encode, decode} = require('blurhash')
const sharp = require('sharp')
3. 利用sharp读取图像并输出为缓冲区。
const {data, info} = await sharp(req.file.path)
.ensureAlpha()
.raw()
.toBuffer({
resolveWithObject: true
});
4.对图像进行blurhash编码,具体参数可改
const blurl = encode(new Uint8ClampedArray(data), info.width, info.height, 4, 4)
至此完成了编码操作
解码
5.解码使用上述encode函数
const decoded = decode(blurl, info.width, info.height)
const image = await sharp(Buffer.from(decoded), {
raw:{
channels: 4,
width: info.width,
height: info.height
}
}).jpeg({
overshootDeringing: true,
quality: 40,
}).toBuffer()
6. 转base64
var base64url = `data:image/png;base64,${image.toString('base64')}`
至此就在Node.js中完成了对图像的处理
引用该案例的和工程文件点击这里
前端效果可以点击南京工业大学远景实验室网站查看