# Java RGB to CMYK Converter

As we already talked about the implementation of how to convert a color pixel value from RGB to CMYK, now I'd like to show you how to convert it from CMYK to RGB.

## Question

RGB to CMYK color matching. Write a java program `RGBtoCMYK` that reads in four command line inputs R, G, B between 0 and 255, and prints the corresponding CMYK values. Devise the appropriate formula by "inverting" the CMYK to RGB 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' = R/255

G' = G/255

B' = B/255

K = 1-max(R', G', B')

C = (1-R'-K) / (1-K)

M = (1-G'-K) / (1-K)

Y = (1-B'-K) / (1-K)
``````

Here the goes the key steps:

1. Pass 3 values matching R, G, B

2. Calculate the CMYK values according to the RGB values

3. Print the CMYK values as `String`

## Solution

``````
/******************************************************************************
*  Compilation:  javac RgbCmykConverter.java
*  Execution:    java RgbCmykConverter R G B
*
*  Convert color values from RGB to CMYK format.
*
*  %  java RgbCmykConverter 0 0 0
*  [0, 0, 0, 100]
*
*  %  java RgbCmykConverter 255 0 0
*  [0, 100, 100, 0]
*
*  %  java RgbCmykConverter 0 0 255
*  [100, 100, 0, 0]
*
******************************************************************************/

import java.util.Arrays;

public class RgbCmykConverter {
public static void main(String[] args) {
int[] cmyk = rgbToCmyk(
Integer.parseInt(args[0]),
Integer.parseInt(args[1]),
Integer.parseInt(args[2])
);

System.out.println(Arrays.toString(cmyk));
}

private static int[] rgbToCmyk(int r, int g, int b) {
double percentageR = r / 255.0 * 100;
double percentageG = g / 255.0 * 100;
double percentageB = b / 255.0 * 100;

double k = 100 - Math.max(Math.max(percentageR, percentageG), percentageB);

if (k == 100) {
return new int[]{ 0, 0, 0, 100 };
}

int c = (int)((100 - percentageR - k) / (100 - k) * 100);
int m = (int)((100 - percentageG - k) / (100 - k) * 100);
int y = (int)((100 - percentageB - k) / (100 - k) * 100);

return new int[]{ c, m, y, (int)k };
}
}
``````

Output

``````-> javac RgbCmykConverter.java

--> java RgbCmykConverter 255 255 255
[0, 0, 0, 0]

-> java RgbCmykConverter 0 255 255
[100, 0, 0, 0]

--> java RgbCmykConverter 0 0 255
[100, 100, 0, 0]``````

The code above is a very simple java code of how to convert a pixel color value from RGB to CMYK.