Libon

Get Image Primary Color

1Mins #HTML#JavaScript#canvas
获取图片的像素, 计算像素的重复次数得到主色调.
1
async function getImagePrimaryColor(imageSrc: string) {
2
// 获取图片的像素数据
3
function getImagePixelData (canvas: HTMLCanvasElement, img:HTMLImageElement) {
4
const context = canvas.getContext('2d')!
5
context.drawImage(img, 0, 0)
6
7
// 获取像素数据
8
const pixelData = context.getImageData(0, 0, canvas.width, canvas.height).data as any as number[]
9
return pixelData
10
}
62 collapsed lines
11
12
// 获取 rgba 像素点的数据和出现的次数并排序
13
function getPrimaryColor (pixelData: number[]) {
14
const colorList = []
15
const rgba = [] as (number | undefined)[]
16
let rgbaStr = ''
17
// 分组循环
18
for (let i = 0; i < pixelData.length; i += 4) {
19
rgba[0] = pixelData[i]
20
rgba[1] = pixelData[i + 1]
21
rgba[2] = pixelData[i + 2]
22
rgba[3] = pixelData[i + 3]
23
24
if (rgba.includes(undefined) || pixelData[i + 3] === 0) {
25
continue
26
}
27
28
rgbaStr = rgba.join(',')
29
if (rgbaStr in colorList) {
30
++colorList[rgbaStr]
31
} else {
32
colorList[rgbaStr] = 1
33
}
34
}
35
36
const arr = [] as { color: string, count: number }[]
37
for (const prop in colorList) {
38
arr.push({
39
// 如果只获取rgb,则为`rgb(${prop})`
40
color: `rgba(${prop})`,
41
count: colorList[prop]
42
})
43
}
44
// 数组排序
45
arr.sort((a, b) => {
46
return b.count - a.count
47
})
48
49
return arr
50
}
51
52
function resolveImage (): Promise<number[]> {
53
return new Promise((resolve, reject) => {
54
try {
55
const canvas = document.createElement('canvas')
56
const img = new Image() // 创建img元素
57
img.src = imageSrc // 设置图片源地址
58
img.onload = () => {
59
resolve(getImagePixelData(canvas, img))
60
}
61
} catch (e) {
62
reject(e)
63
}
64
})
65
}
66
67
return getPrimaryColor(await resolveImage())
68
}
69
70
71
// 获取得到后的数据的第 0 位
72
console.log(getImagePrimaryColor("./test.jpeg"))

CD ..
接下来阅读
.npmrc config file