Almost everyone knows the RGB color model, red, green and blue, especially as a software engineer. It's widely applied in many industries. The CMYK, stands for "Cyan Magenta Yellow Black", is mostly used in paper print. Today we are going to create a java program to convert a color from CMYK to RGB.
Question
CMYK to RGB color matching. Write a java program
CMYKtoRGB
that reads in four command line inputs C, M, Y, and K between 0 and 100, and prints the corresponding RGB parameters. Devise the appropriate formula by "inverting" the RGB to CMYK conversion formula.
Implementing Steps
The CMYK color model has 4 color values from 0 to 100, and the RGB color model has 3 color values from 0 to 255. The formula is very simple and listed in the code.
Here is the formula
R = 255 × (1-C) × (1-K)
G = 255 × (1-M) × (1-K)
B = 255 × (1-Y) × (1-K)
Here the goes the key steps:
- Pass 4 CMYK values as command line parameters
- Calculate the RGB values according to the CMYK values
- Print the RGB values as
String
Solution
/******************************************************************************
* Compilation: javac CmykRgbConverter.java
* Execution: java CmykRgbConverter c m y k
*
* Convert color values from CMYK to RGB format.
*
* % java CmykRgbConverter 0 0 0 0
* [255, 255, 255]
*
* % java CmykRgbConverter 0 0 0 100
* [0, 0, 0]
*
* % java CmykRgbConverter 100 0 100 0
* [0, 255, 0]
*
******************************************************************************/
import java.util.Arrays;
public class CmykRgbConverter {
public static void main(String[] args) {
int[] rgb = cmykToRgb(
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2]),
Integer.parseInt(args[3])
);
System.out.println(Arrays.toString(rgb));
}
private static int[] cmykToRgb(int c, int m, int y, int k) {
int r = 255 * (1 - c/100) * (1 - k/100);
int g = 255 * (1 - m/100) * (1 - k/100);
int b = 255 * (1 - y/100) * (1 - k/100);
int[] rgb = new int[]{ r, g, b };
return rgb;
}
}
Output
-> javac CmykRgbConverter.java
-> java CmykRgbConverter 0 0 0 0
[255, 255, 255]
-> java CmykRgbConverter 0 100 100 0
[255, 0, 0]
-> java CmykRgbConverter 0 100 100 100
[0, 0, 0]
The code above is a very simple java code of how to convert a pixel color value from CMYK to RGB.