This repository was archived by the owner on Dec 2, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathresembleImage.js
More file actions
70 lines (65 loc) · 2 KB
/
Copy pathresembleImage.js
File metadata and controls
70 lines (65 loc) · 2 KB
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
import Jimp from 'jimp';
function scaleValue (value, min, max) {
const newMin = 0;
const newMax = 100;
const percent = (value - min) / (max - min);
return percent * (newMax - newMin) + newMin;
}
function colourStopFactory (width) {
return function colourStop (colour, index) {
return {
colour,
position: scaleValue(index, 0, width),
};
};
}
function resolveFidelity (width, pair) {
if (!pair) {
throw new Error('Expected a <number> or <percentage> value for fidelity.');
}
const number = parseFloat(pair.number);
if (number === 0) {
throw new Error('Expected a fidelity greater than 0.');
}
if (pair.unit === '%') {
return width * (number / 100);
}
return number;
}
function rgbToHex ({r, g, b}) {
function convert (c) {
const hex = c.toString(16);
return hex.length === 1 ? '0' + hex : hex;
}
return '#' + convert(r) + convert(g) + convert(b);
}
export default function resembleImage (path, {generator, fidelity}) {
return new Promise((resolve, reject) => {
Jimp.read(path, (err, image) => {
if (err) {
reject(err);
}
let width;
let height;
let chunk;
try {
width = image.bitmap.width;
height = image.bitmap.height;
chunk = resolveFidelity(width, fidelity);
} catch (e) {
return reject(e);
}
const stops = [];
const colourStop = colourStopFactory(width);
for (let i = 0; i < width; i += chunk) {
let color = image.clone()
.crop(i, 0, chunk, height)
.resize(1, 1, Jimp.RESIZE_BICUBIC)
.getPixelColor(0, 0);
color = rgbToHex(Jimp.intToRGBA(color));
stops.push(colourStop(color, i));
}
return resolve(generator(stops));
});
});
}