RGB to CMYK and back algorithm
To accurately convert values from RGB to CMYK and vice versa, the way Photoshop does, you need to use an ICC color profile. All the simple algorithmic solutions you'll find in the interwebs (like the one posted above) are inacurrate and produce colors that are outside the CMYK color gamut (for example they convert CMYK(100, 0, 0, 0) to rgb(0, 255, 255) which is obviously wrong since rgb(0, 255, 255) can't be reproduced with CMYK). Look into the java.awt.color.ICC_ColorSpace and java.awt.color.ICC_Profile classes for converting colors using ICC color profiles. As for the color profile files themselves, Adobe distributes them for free.
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();
}
}
}
A better way to do it:
try {
// The "from" CMYK colorspace
ColorSpace cmykColorspace = new ICC_ColorSpace(ICC_Profile.getInstance("icc/CoatedFOGRA27.icc"));
// The "to" RGB colorspace
ColorSpace rgbColorspace = new ICC_ColorSpace(ICC_Profile.getInstance("icc/AdobeRGB1998.icc"));
// Bring in to CIEXYZ colorspace (refer to Java documentation: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/color/ColorSpace.html)
float[] ciexyz = cmykColorspace.toCIEXYZ(cmyk);
float[] thisColorspace = rgbColorspace.fromCIEXYZ(ciexyz);
float[] rgb = thisColorspace;
Color c = new Color(rgb[0], rgb[1], rgb[2]);
// Format RGB as Hex and return
return String.format("#%06x", c.getRGB() & 0xFFFFFF);
} catch (IOException e) { e.printStackTrace(); }