LabColor.fromRGB constructor

LabColor.fromRGB(
  1. int red,
  2. int green,
  3. int blue
)

Constructs a LabColor from a RGB color.

Reference: https://gist.github.com/manojpandey/f5ece715132c572c80421febebaf66ae

Implementation

factory LabColor.fromRGB(int red, int green, int blue) {
  List<num> rgb = [red, green, blue].map((int channel) {
    double value = channel / 255;
    if (value > 0.04045) {
      value = pow(((value + 0.055) / 1.055), 2.4).toDouble();
    } else {
      value /= 12.92;
    }
    return value * 100;
  }).toList();

  List<num> xyz = [
    (rgb[0] * 0.4124 + rgb[1] * 0.3576 + rgb[2] * 0.1805) / 95.047,
    (rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722) / 100,
    (rgb[0] * 0.0193 + rgb[1] * 0.1192 + rgb[2] * 0.9505) / 108.883,
  ].map((double value) {
    if (value > 0.008856) {
      return pow(value, (1 / 3).toDouble());
    } else {
      return (7.787 * value) + (16 / 116);
    }
  }).toList();

  return LabColor(
    (116.0 * xyz[1]) - 16,
    500.0 * (xyz[0] - xyz[1]),
    200.0 * (xyz[1] - xyz[2]),
  );
}