|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 /** |
|
6 * Given a color in the Lab space, return its chroma (colorfulness, |
|
7 * saturation). |
|
8 * |
|
9 * @param lab |
|
10 * The lab color to get the chroma from |
|
11 * |
|
12 * @return A number greater than zero that measures chroma in the image |
|
13 */ |
|
14 function labChroma(lab) { |
|
15 return Math.sqrt(Math.pow(lab.a, 2) + Math.pow(lab.b, 2)); |
|
16 } |
|
17 |
|
18 /** |
|
19 * Given the RGB components of a color as integers from 0-255, return the |
|
20 * color in the XYZ color space. |
|
21 * |
|
22 * @return An object with x, y, z properties holding those components of the |
|
23 * color in the XYZ color space. |
|
24 */ |
|
25 function rgb2xyz(r, g, b) { |
|
26 r /= 255; |
|
27 g /= 255; |
|
28 b /= 255; |
|
29 |
|
30 // assume sRGB |
|
31 r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92); |
|
32 g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92); |
|
33 b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92); |
|
34 |
|
35 return { |
|
36 x: ((r * 0.4124) + (g * 0.3576) + (b * 0.1805)) * 100, |
|
37 y: ((r * 0.2126) + (g * 0.7152) + (b * 0.0722)) * 100, |
|
38 z: ((r * 0.0193) + (g * 0.1192) + (b * 0.9505)) * 100 |
|
39 }; |
|
40 } |
|
41 |
|
42 /** |
|
43 * Given the RGB components of a color as integers from 0-255, return the |
|
44 * color in the Lab color space. |
|
45 * |
|
46 * @return An object with lightness, a, b properties holding those components |
|
47 * of the color in the Lab color space. |
|
48 */ |
|
49 function rgb2lab(r, g, b) { |
|
50 let xyz = rgb2xyz(r, g, b), |
|
51 x = xyz.x / 95.047, |
|
52 y = xyz.y / 100, |
|
53 z = xyz.z / 108.883; |
|
54 |
|
55 x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116); |
|
56 y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116); |
|
57 z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116); |
|
58 |
|
59 return { |
|
60 lightness: (116 * y) - 16, |
|
61 a: 500 * (x - y), |
|
62 b: 200 * (y - z) |
|
63 }; |
|
64 } |