toolkit/components/places/ColorConversion.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/toolkit/components/places/ColorConversion.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,64 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +
     1.8 +/**
     1.9 + * Given a color in the Lab space, return its chroma (colorfulness,
    1.10 + * saturation).
    1.11 + *
    1.12 + * @param lab
    1.13 + *        The lab color to get the chroma from
    1.14 + *
    1.15 + * @return A number greater than zero that measures chroma in the image
    1.16 + */
    1.17 +function labChroma(lab) {
    1.18 +  return Math.sqrt(Math.pow(lab.a, 2) + Math.pow(lab.b, 2));
    1.19 +}
    1.20 +
    1.21 +/**
    1.22 + * Given the RGB components of a color as integers from 0-255, return the
    1.23 + * color in the XYZ color space.
    1.24 + *
    1.25 + * @return An object with x, y, z properties holding those components of the
    1.26 + *         color in the XYZ color space.
    1.27 + */
    1.28 +function rgb2xyz(r, g, b) {
    1.29 +  r /= 255;
    1.30 +  g /= 255;
    1.31 +  b /= 255;
    1.32 +
    1.33 +  // assume sRGB
    1.34 +  r = r > 0.04045 ? Math.pow(((r + 0.055) / 1.055), 2.4) : (r / 12.92);
    1.35 +  g = g > 0.04045 ? Math.pow(((g + 0.055) / 1.055), 2.4) : (g / 12.92);
    1.36 +  b = b > 0.04045 ? Math.pow(((b + 0.055) / 1.055), 2.4) : (b / 12.92);
    1.37 +
    1.38 +  return {
    1.39 +    x: ((r * 0.4124) + (g * 0.3576) + (b * 0.1805)) * 100,
    1.40 +    y: ((r * 0.2126) + (g * 0.7152) + (b * 0.0722)) * 100,
    1.41 +    z: ((r * 0.0193) + (g * 0.1192) + (b * 0.9505)) * 100
    1.42 +  };
    1.43 +}
    1.44 +
    1.45 +/**
    1.46 + * Given the RGB components of a color as integers from 0-255, return the
    1.47 + * color in the Lab color space.
    1.48 + *
    1.49 + * @return An object with lightness, a, b properties holding those components
    1.50 + *         of the color in the Lab color space.
    1.51 + */
    1.52 +function rgb2lab(r, g, b) {
    1.53 +  let xyz = rgb2xyz(r, g, b),
    1.54 +        x = xyz.x / 95.047,
    1.55 +        y = xyz.y / 100,
    1.56 +        z = xyz.z / 108.883;
    1.57 +
    1.58 +  x = x > 0.008856 ? Math.pow(x, 1/3) : (7.787 * x) + (16 / 116);
    1.59 +  y = y > 0.008856 ? Math.pow(y, 1/3) : (7.787 * y) + (16 / 116);
    1.60 +  z = z > 0.008856 ? Math.pow(z, 1/3) : (7.787 * z) + (16 / 116);
    1.61 +
    1.62 +  return {
    1.63 +    lightness: (116 * y) - 16,
    1.64 +    a:  500 * (x - y),
    1.65 +    b:  200 * (y - z)
    1.66 +  };
    1.67 +}

mercurial