2023-06-12 21:15:23 +10:00
|
|
|
import { encode } from 'blurhash';
|
|
|
|
|
|
|
|
|
|
export const encodeBlurHash = (
|
|
|
|
|
img: HTMLImageElement | HTMLVideoElement,
|
|
|
|
|
width?: number,
|
|
|
|
|
height?: number
|
|
|
|
|
): string | undefined => {
|
2023-10-06 13:44:06 +11:00
|
|
|
const imgWidth = img instanceof HTMLVideoElement ? img.videoWidth : img.width;
|
|
|
|
|
const imgHeight = img instanceof HTMLVideoElement ? img.videoHeight : img.height;
|
2023-06-12 21:15:23 +10:00
|
|
|
const canvas = document.createElement('canvas');
|
2023-10-06 13:44:06 +11:00
|
|
|
canvas.width = width || imgWidth;
|
|
|
|
|
canvas.height = height || imgHeight;
|
2023-06-12 21:15:23 +10:00
|
|
|
const context = canvas.getContext('2d');
|
|
|
|
|
|
|
|
|
|
if (!context) return undefined;
|
|
|
|
|
context.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
|
|
|
const data = context.getImageData(0, 0, canvas.width, canvas.height);
|
|
|
|
|
return encode(data.data, data.width, data.height, 4, 4);
|
|
|
|
|
};
|