I'm looking for an algorithm to convert an RGB color to CMYK. Photoshop is performing the conversion below:
R = 220 G = 233 B = 174
C = 15 M = 0 Y = 40 K = 0
I agree with the previous answers, but I want to say that:
if ( K == 1 )
{
C = 0
M = 0
Y = 0
}
It can be if r = g = b = 0.
Check out this link: http://www.codeproject.com/KB/applications/xcmyk.aspx. It gives this formula.
Black = minimum(1-Red,1-Green,1-Blue)
Cyan = (1-Red-Black)/(1-Black)
Magenta = (1-Green-Black)/(1-Black)
Yellow = (1-Blue-Black)/(1-Black)
My complete example for C# conversion between CMYK <-> HEX:
public class ColorConverter
{
public static string CMYKtoHex(decimal[] cmyk)
{
if (cmyk.Length != 4) return null;
var r = (int)(255 * (1 - cmyk[0]) * (1 - cmyk[3]));
var g = (int)(255 * (1 - cmyk[1]) * (1 - cmyk[3]));
var b = (int)(255 * (1 - cmyk[2]) * (1 - cmyk[3]));
var hex = "#" + r.ToString("X2") + g.ToString("X2") + b.ToString("X2");
return hex;
}
public static decimal[] HexToCMYK(string hex)
{
decimal computedC = 0;
decimal computedM = 0;
decimal computedY = 0;
decimal computedK = 0;
hex = (hex[0] == '#') ? hex.Substring(1, 6) : hex;
if (hex.Length != 6)
{
return null;
}
decimal r = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
decimal g = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
decimal b = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
// BLACK
if (r == 0 && g == 0 && b == 0)
{
computedK = 1;
return new[] { 0, 0, 0, computedK };
}
computedC = 1 - (r / 255);
computedM = 1 - (g / 255);
computedY = 1 - (b / 255);
var minCMY = Math.Min(computedC, Math.Min(computedM, computedY));
computedC = (computedC - minCMY) / (1 - minCMY);
computedM = (computedM - minCMY) / (1 - minCMY);
computedY = (computedY - minCMY) / (1 - minCMY);
computedK = minCMY;
return new[] { computedC, computedM, computedY, computedK };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With