Matthew Hipkin

Convert between TColor and CMYK with Delphi and Lazarus

Download: https://github.com/hippy2094/codelib/tree/master/cymk-delphi-lazarus

Converting between a TColor and CMYK is a pretty easy process, first up you need to specify a record type to hold the CMYK values:

type
  TCMYKColor = record
    C: Double;
    M: Double;
    Y: Double;
    K: Double;
  end;

Using this formula we can convert the RGB into CMYK with the following function.

function RGBToCMYK(c: TColor): TCMYKColor;
var
  r,g,b,k: Double;
begin
  r := 1 - (Red(c) / 255);
  g := 1 - (Green(c) / 255);
  b := 1 - (Blue(c) / 255);
  k := min(r,min(g,b));
  if c = 0 then
  begin
    Result.C := 0.00;
    Result.M := 0.00;
    Result.Y := 0.00;
    Result.K := 1.00;
  end
  else
  begin
    Result.C := (r - k) / (1 - k);
    Result.M := (g - k) / (1 - k);
    Result.Y := (b - k) / (1 - k);
    Result.K := k;
  end;
end;

And then back again with this one.

function CMYKToRGB(c: TCMYKColor): TColor;
var
  r,g,b: Byte;
begin
  r := Round(255 * (1-c.C) * (1-c.K));
  g := Round(255 * (1-c.M) * (1-c.K));
  b := Round(255 * (1-c.Y) * (1-c.K));
  Result := RGBToColor(r,g,b);  // Delphi users should use the RGB() function instead
end;

To display the CMYK value as a string, a simple helper function:

function CMYKToString(c: TCMYKColor): String;
begin
  Result := FloatToStrF(c.C, ffGeneral, 3, 3);
  Result := Result + ',';
  Result := Result + FloatToStrF(c.M, ffGeneral, 3, 3);
  Result := Result + ',';
  Result := Result + FloatToStrF(c.Y, ffGeneral, 3, 3);
  Result := Result + ',';
  Result := Result + FloatToStrF(c.K, ffGeneral, 3, 3);
end;

You can download the full unit here.

blog comments powered by Disqus