Converts color components from the sRGB to the CIE XYZ color space. - Java Swing

Java examples for Swing:JComponent

Description

Converts color components from the sRGB to the CIE XYZ color space.

Demo Code


//package com.java2s;

public class Main {
    /**//  w  ww .j  ava 2s  . c om
     * sRGB to CIE XYZ conversion matrix. See
     * http://www.brucelindbloom.com/index.html?WorkingSpaceInfo.html#Specifications *
     */
    private static final double[] MATRIX_SRGB2XYZ_D50 = { 0.436052025,
            0.385081593, 0.143087414, 0.222491598, 0.716886060,
            0.060621486, 0.013929122, 0.097097002, 0.714185470 };

    /**
     * Converts color components from the sRGB to the CIE XYZ color space.
     * A D50 white point is assumed for the sRGB conversion. If the <i>xyz</i>
     * array is {@code null}, a new one will be created with the same
     * size as the <i>rgb</i> array.
     *
     * See http://www.brucelindbloom.com/index.html?Eqn_RGB_to_XYZ.html
     *
     * @param rgb Color components in the sRGB color space.
     * @param xyz Optional array to store color components in the CIE XYZ color
     *            space.
     * @return Color components in the CIE XYZ color space.
     */
    public static double[] rgb2xyz(double[] rgb, double[] xyz) {
        if (xyz == null) {
            xyz = new double[rgb.length];
        }

        // Remove sRGB companding to make RGB components linear
        double[] rgbLin = new double[rgb.length];
        for (int i = 0; i < rgb.length; i++) {
            if (rgb[i] <= 0.04045) {
                rgbLin[i] = rgb[i] / 12.92;
            } else {
                rgbLin[i] = Math.pow((rgb[i] + 0.055) / 1.055, 2.4);
            }
        }

        // Convert linear sRGB with D50 white point to CIE XYZ
        for (int i = 0; i < xyz.length; i++) {
            xyz[i] = MATRIX_SRGB2XYZ_D50[i * 3 + 0] * rgbLin[0]
                    + MATRIX_SRGB2XYZ_D50[i * 3 + 1] * rgbLin[1]
                    + MATRIX_SRGB2XYZ_D50[i * 3 + 2] * rgbLin[2];
        }

        return xyz;
    }
}

Related Tutorials