1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.graphics.cts.utils;
18 
19 import android.graphics.Color;
20 
21 /**
22  * Copied from frameworks/base/core to support CAM library for SystemPalette CTS test
23  *
24  * A set of color-related utility methods, building upon those available in {@code Color}.
25  */
26 public final class ColorUtils {
27 
28     private static final double XYZ_WHITE_REFERENCE_X = 95.047;
29     private static final double XYZ_WHITE_REFERENCE_Y = 100;
30     private static final double XYZ_WHITE_REFERENCE_Z = 108.883;
31     private static final double XYZ_EPSILON = 0.008856;
32     private static final double XYZ_KAPPA = 903.3;
33 
34     /**
35      * Converts a color from CIE XYZ to its RGB representation.
36      *
37      * <p>This method expects the XYZ representation to use the D65 illuminant and the CIE
38      * 2° Standard Observer (1931).</p>
39      *
40      * @param x X component value [0...95.047)
41      * @param y Y component value [0...100)
42      * @param z Z component value [0...108.883)
43      * @return int containing the RGB representation
44      */
xyzToColor(double x, double y, double z)45     public static int xyzToColor(double x, double y, double z) {
46         double r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100;
47         double g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100;
48         double b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100;
49 
50         r = r > 0.0031308 ? 1.055 * Math.pow(r, 1 / 2.4) - 0.055 : 12.92 * r;
51         g = g > 0.0031308 ? 1.055 * Math.pow(g, 1 / 2.4) - 0.055 : 12.92 * g;
52         b = b > 0.0031308 ? 1.055 * Math.pow(b, 1 / 2.4) - 0.055 : 12.92 * b;
53 
54         return Color.rgb(
55                 (int) constrain((int) Math.round(r * 255), 0, 255),
56                 (int) constrain((int) Math.round(g * 255), 0, 255),
57                 (int) constrain((int) Math.round(b * 255), 0, 255));
58     }
59 
constrain(float amount, float low, float high)60     private static float constrain(float amount, float low, float high) {
61         return amount < low ? low : (amount > high ? high : amount);
62     }
63 }
64