Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert RGB color to CMYK?

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

like image 459
Junior Developer Avatar asked Mar 11 '10 15:03

Junior Developer


3 Answers

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.

like image 197
Artem Ryblov Avatar answered Sep 30 '22 09:09

Artem Ryblov


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) 
like image 34
37Stars Avatar answered Sep 30 '22 09:09

37Stars


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 };
    }
 }
like image 40
Martin S Avatar answered Sep 30 '22 11:09

Martin S