You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Flutter中如何将RGB值转换为CIELAB(L*a*b*)色彩值

Flutter中RGB值转CIELAB色彩空间实现方案

方案1:使用第三方库实现(推荐)

直接使用成熟的色彩转换库flutter_color_models,省去手动写转换逻辑的成本:

  • 第一步:在pubspec.yaml中添加依赖
dependencies:
  flutter:
    sdk: flutter
  flutter_color_models: ^1.3.2 # 可替换为pub.dev上的最新稳定版本
  • 第二步:调用转换API,示例代码如下
import 'package:flutter_color_models/flutter_color_models.dart';

void main() {
  // 传入你要转换的RGB值
  final sourceRgb = RgbColor(253, 216, 28);
  // 直接转换为CIELAB格式
  final labColor = sourceRgb.toLabColor();

  // 输出转换结果
  print('L*值:${labColor.l.toStringAsFixed(2)}');
  print('a*值:${labColor.a.toStringAsFixed(2)}');
  print('b*值:${labColor.b.toStringAsFixed(2)}');
  // 你提供的这组RGB转换后结果约为 L*:87.80、a*:-5.61、b*:84.18,不同白点参数会有细微差异
}

方案2:手动实现转换逻辑(无第三方依赖)

如果不想引入额外依赖,可以自己实现标准转换流程:先将sRGB转换为XYZ色彩空间,再将XYZ转换为CIELAB,默认采用通用的D65白点标准,可直接复用以下代码:

import 'dart:math';

class RgbToLabConverter {
  // sRGB转XYZ色彩空间
  static List<double> _rgbToXyz(int r, int g, int b) {
    // 归一化0-255数值到0-1区间
    double rf = r / 255.0;
    double gf = g / 255.0;
    double bf = b / 255.0;

    // 执行Gamma校正
    rf = rf > 0.04045 ? pow((rf + 0.055) / 1.055, 2.4).toDouble() : rf / 12.92;
    gf = gf > 0.04045 ? pow((gf + 0.055) / 1.055, 2.4).toDouble() : gf / 12.92;
    bf = bf > 0.04045 ? pow((bf + 0.055) / 1.055, 2.4).toDouble() : bf / 12.92;

    rf *= 100;
    gf *= 100;
    bf *= 100;

    // 应用sRGB转XYZ转换矩阵
    double x = rf * 0.4124564 + gf * 0.3575761 + bf * 0.1804375;
    double y = rf * 0.2126729 + gf * 0.7151522 + bf * 0.0721750;
    double z = rf * 0.0193339 + gf * 0.1191920 + bf * 0.9503041;

    return [x, y, z];
  }

  // XYZ转CIELAB色彩空间
  static List<double> _xyzToLab(double x, double y, double z) {
    // D65白点参考值
    const double xRef = 95.047;
    const double yRef = 100.000;
    const double zRef = 108.883;

    double xr = x / xRef;
    double yr = y / yRef;
    double zr = z / zRef;

    // 应用转换函数
    xr = xr > 0.008856 ? pow(xr, 1/3).toDouble() : (7.787 * xr) + 16 / 116;
    yr = yr > 0.008856 ? pow(yr, 1/3).toDouble() : (7.787 * yr) + 16 / 116;
    zr = zr > 0.008856 ? pow(zr, 1/3).toDouble() : (7.787 * zr) + 16 / 116;

    double l = 116 * yr - 16;
    double a = 500 * (xr - yr);
    double b = 200 * (yr - zr);

    return [l, a, b];
  }

  // 对外暴露的RGB转LAB入口方法
  static List<double> convert(int r, int g, int b) {
    final xyz = _rgbToXyz(r, g, b);
    return _xyzToLab(xyz[0], xyz[1], xyz[2]);
  }
}

// 调用示例
void main() {
  final labResult = RgbToLabConverter.convert(253, 216, 28);
  print('L*: ${labResult[0].toStringAsFixed(2)}');
  print('a*: ${labResult[1].toStringAsFixed(2)}');
  print('b*: ${labResult[2].toStringAsFixed(2)}');
}

内容的提问来源于stack exchange,提问作者zeewa42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:06:04