-
Notifications
You must be signed in to change notification settings - Fork 3
/
blur.tsx
73 lines (62 loc) · 1.81 KB
/
blur.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import { useEffect, useRef } from "react";
import { encode, decode } from "blurhash";
const loadImage = async (src) =>
new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = (...args) => reject(args);
img.src = src;
});
const getImageData = (image) => {
const canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
return context.getImageData(0, 0, image.width, image.height);
};
function getFileDataURL(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (event) {
const dataURL = event.target.result;
resolve(dataURL);
};
reader.onerror = function (error) {
reject(error);
};
});
}
export async function getBlurhashFromFile(file) {
const imageUrl = await getFileDataURL(file);
const image = await loadImage(imageUrl);
const imageData = getImageData(image);
return {
blurhash: encode(imageData.data, imageData.width, imageData.height, 4, 3),
width: imageData.width,
height: imageData.height,
};
}
export function BlurhashImage({ blurhash, width, height, alt, ...props }) {
const canvasRef = useRef(null);
useEffect(() => {
const canvas = canvasRef.current;
if (canvas) {
const ctx = canvas.getContext("2d");
const pixels = decode(blurhash, width, height);
const imageData = ctx.createImageData(width, height);
imageData.data.set(pixels);
ctx.putImageData(imageData, 0, 0);
}
}, [blurhash, width, height]);
return (
<canvas
ref={canvasRef}
width={width}
height={height}
alt={alt}
{...props}
/>
);
}