Java – RGB to CMYK and return algorithm
•
Java
I try to implement a solution to calculate the conversion between RGB and CMYK, and vice versa This is me 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,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,B}; } }
Solution
As lea verou said, you should use color space information because there is no algorithm to map RGB to CMYK Adobe has some ICC color profiles to download 1, but I don't know how they are licensed
Once you have a color profile, work as follows:
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(); } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码