This repository has been archived by the owner on Dec 5, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getColor.js
61 lines (50 loc) · 1.72 KB
/
getColor.js
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
"use strict";
const { createCanvas, loadImage } = require("canvas");
const Color = require("color");
/**
* Get color at pixel with coordinate [x, y]
* https://stackoverflow.com/questions/3528299/get-pixel-color-of-base64-png-using-javascript
* @param data: 1D array of RGBA values
* @param width: width of the image
* @param coordinate: [x, y] pixel in the image
* @return hex color
*/
function getColorAt(data, width, coordinate) {
const RGBA_LEN = 4;
const [x, y] = coordinate;
const index = (y * width + x) * RGBA_LEN;
const [r, g, b, a] = data.slice(index, index + RGBA_LEN);
return Color(`rgba(${r},${g},${b},${a})`).hex();
}
/**
* Get image background color.
* If the color is inconsistent, return light grey.
* @param data: 1D array of RGBA values
* @param dimensions: [width, height] of the image
* @return color as a hex string
*/
function getImageBackground(data, dimensions) {
const [width, height] = dimensions;
const topMid = [width / 2, 1];
const bgColor1 = getColorAt(data, width, topMid);
const leftMid = [1, height / 2];
const bgColor2 = getColorAt(data, width, leftMid);
if (bgColor1 !== bgColor2) {
return "#F4F5F7";
}
return bgColor1;
}
/** Use node-canvas to get the logo style */
async function getBackgroundColor(base64Str) {
const src = `data:image/gif;base64, ${base64Str}`;
const image = await loadImage(src);
const canvas = createCanvas(image.width, image.height);
const context = canvas.getContext("2d");
context.drawImage(image, 0, 0);
const imageData = context.getImageData(0, 0, image.width, image.height);
const data = Object.values(imageData.data);
return getImageBackground(data, [image.width, image.height]);
}
module.exports = {
getBackgroundColor,
};