RGB and CMYK are two main color models used for digital displays and printing, respectively. If you are working with design or printing, you may need to convert colors from RGB to CMYK. We have already made a post about how to convert CMYK to RGB. Let's consider the reverse conversion.
What are RGB and CMYK?
- RGB (Red, Green, Blue) is an additive model used on screens. The more light is added, the brighter the colors.
- CMYK (Cyan, Magenta, Yellow, Black) is a subtractive model used in printers. The more ink is added, the darker the color becomes.
Formula for converting RGB → CMYK
To convert RGB to CMYK, use the following formula:
- Determine the color values in the range from 0 to 1 (divide the RGB values by 255).
-
Calculate the value of K:
K = 1 - max(R, G, B) -
Calculate the values of C, M, Y:
C = (1 - R - K) / (1 - K) M = (1 - G - K) / (1 - K) Y = (1 - B - K) / (1 - K)(If K = 1, then C = M = Y = 0.)
Example code in JavaScript
function rgbToCmyk(r, g, b) {
let rNorm = r / 255, gNorm = g / 255, bNorm = b / 255;
let k = 1 - Math.max(rNorm, gNorm, bNorm);
let c = (1 - rNorm - k) / (1 - k) || 0;
let m = (1 - gNorm - k) / (1 - k) || 0;
let y = (1 - bNorm - k) / (1 - k) || 0;
return `cmyk(${(c * 100).toFixed(1)}%, ${(m * 100).toFixed(1)}%, ${(y * 100).toFixed(1)}%, ${(k * 100).toFixed(1)}%)`;
}
This function takes RGB values in the range from 0 to 255 and returns the corresponding CMYK values in percentages.