JF Beaulieu - 17 days ago 7
Java Question

# RGB to CMYK and back algorithm

I am trying to implement a solution for calculating the conversion between RGB and CMYK and vice versa. Here is what I have so far:

``````  public static int[] rgbToCmyk(int red, int green, int blue)
{
int black = Math.min(Math.min(255 - red, 255 - green), 255 - blue);

if (black!=255) {
int cyan    = (255-red-black)/(255-black);
int magenta = (255-green-black)/(255-black);
int yellow  = (255-blue-black)/(255-black);
return new int[] {cyan,magenta,yellow,black};
} else {
int cyan = 255 - red;
int magenta = 255 - green;
int yellow = 255 - blue;
return new int[] {cyan,magenta,yellow,black};
}
}

public static int[] cmykToRgb(int cyan, int magenta, int yellow, int black)
{
if (black!=255) {
int R = ((255-cyan) * (255-black)) / 255;
int G = ((255-magenta) * (255-black)) / 255;
int B = ((255-yellow) * (255-black)) / 255;
return new int[] {R,G,B};
} else {
int R = 255 - cyan;
int G = 255 - magenta;
int B = 255 - yellow;
return new int[] {R,G,B};
}
}
``````

As Lea Verou said you should make use of color space information because there isn't an algorithm to map from RGB to CMYK. Adobe has some ICC color profiles available for download1, but I'm not sure how they are licensed.

Once you have the color profiles something like the following would do the job:

``````import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_Profile;
import java.io.IOException;
import java.util.Arrays;

public class ColorConv {
final static String pathToCMYKProfile = "C:\\UncoatedFOGRA29.icc";

public static float[] rgbToCmyk(float... rgb) throws IOException {
if (rgb.length != 3) {
throw new IllegalArgumentException();
}
ColorSpace instance = new ICC_ColorSpace(ICC_Profile.getInstance(pathToCMYKProfile));
float[] fromRGB = instance.fromRGB(rgb);
return fromRGB;
}
public static float[] cmykToRgb(float... cmyk) throws IOException {
if (cmyk.length != 4) {
throw new IllegalArgumentException();
}
ColorSpace instance = new ICC_ColorSpace(ICC_Profile.getInstance(pathToCMYKProfile));
float[] fromRGB = instance.toRGB(cmyk);
return fromRGB;
}

public static void main(String... args) {
try {
float[] rgbToCmyk = rgbToCmyk(1.0f, 1.0f, 1.0f);
System.out.println(Arrays.toString(rgbToCmyk));
System.out.println(Arrays.toString(cmykToRgb(rgbToCmyk[0], rgbToCmyk[1], rgbToCmyk[2], rgbToCmyk[3])));
} catch (IOException e) {
e.printStackTrace();
}
}
}
``````
Source (Stackoverflow)