+48
utils/mean-color.ts
+48
utils/mean-color.ts
···
1
+
import sharp from "sharp";
2
+
3
+
const cache = new Map<string, string>();
4
+
5
+
export default async function getMeanColor(url: string) {
6
+
7
+
const cached = cache.get(url);
8
+
if (cached) return cached;
9
+
10
+
const { data } = await sharp(
11
+
await (await fetch(url)).arrayBuffer()
12
+
)
13
+
.raw()
14
+
.toBuffer({ resolveWithObject: true });
15
+
16
+
const colorCountMap = new Map<string, number>();
17
+
18
+
for (let i = 0; i < data.length; i += 4) {
19
+
const red = data[i];
20
+
const green = data[i + 1];
21
+
const blue = data[i + 2];
22
+
23
+
const color = `${red},${green},${blue}`;
24
+
25
+
if (colorCountMap.has(color)) {
26
+
colorCountMap.set(color, colorCountMap.get(color)! + 1);
27
+
} else {
28
+
colorCountMap.set(color, 1);
29
+
}
30
+
}
31
+
32
+
let maxCount = 0;
33
+
let mostFrequentColor = "";
34
+
35
+
for (const [color, count] of colorCountMap.entries()) {
36
+
if (count > maxCount) {
37
+
maxCount = count;
38
+
mostFrequentColor = color;
39
+
}
40
+
}
41
+
42
+
const [red, green, blue] = mostFrequentColor.split(",").map(Number);
43
+
const hex = `#${red.toString(16).padStart(2, "0")}${green.toString(16).padStart(2, "0")}${blue.toString(16).padStart(2, "0")}`;
44
+
45
+
cache.set(url, hex);
46
+
47
+
return hex;
48
+
}