开发者

How can I calculate differences (luminosity, brightness, color) between two colors?

How can I calculate

  • the luminosity contrast ratio,
  • the difference in brightness, and
  • the difference in color

between two given colors?

开发者_如何学C

Example:

Input

  • color 1 : #99ccff
  • color 2: #225588

Output

  • luminosity contrast ratio : 4.57 : 1
  • difference in brightness : 119
  • difference in color : 357


Convert each colour from (R, G, B) to (H, S, V) [or (H, S, L)] coordinates. You can find formulae at Wikipedia.

I have written Pascal functions for this:

function RGBToHSV(const Color: TRGB): THSV;
var
  cmax, cmin, cdiff: real;
begin
  cmax := MaxComponent(Color);
  cmin := MinComponent(Color);
  cdiff := cmax - cmin;

  with Color, result do
  begin

    // Hue
    if cmax = cmin then
      hsvHue := 0
    else if cmax = rgbRed then
      hsvHue := (60 * (rgbGreen - rgbBlue) / cdiff)
    else if cmax = rgbGreen then
      hsvHue := (60 * (rgbBlue - rgbRed) / cdiff) + 120
    else
      hsvHue := (60 * (rgbRed - rgbGreen) / cdiff) + 240;

    hsvHue := Fix360(hsvHue);

    // Saturation
    if cmax = 0 then
      hsvSaturation := 0
    else
      hsvSaturation := 1 - cmin / cmax;

    // Value
    hsvValue := cmax;

  end;

end;

function RGBToHSL(const Color: TRGB): THSL;
var
  cmax, cmin, cdiff, csum: real;
begin
  cmax := MaxComponent(Color);
  cmin := MinComponent(Color);
  cdiff := cmax - cmin;
  csum := cmax + cmin;

  with Color, result do
  begin

    // Hue
    if cmax = cmin then
      hslHue := 0
    else if cmax = rgbRed then
      hslHue := (60 * (rgbGreen - rgbBlue) / cdiff)
    else if cmax = rgbGreen then
      hslHue := (60 * (rgbBlue - rgbRed) / cdiff) + 120
    else
      hslHue := (60 * (rgbRed - rgbGreen) / cdiff) + 240;

    hslHue := Fix360(hslHue);

    // Saturation
    if cmax = cmin then
      hslSaturation := 0
    else if csum <= 1 then
      hslSaturation := cdiff / csum
    else
      hslSaturation := cdiff / (2 - csum);

    // Lightness
    hslLightness := csum / 2;

  end;

end;    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜