RGB-to-CMYK Conversion

Question: How do I convert a color from RGB model to CMYK model in JavaScript?

Answer: The CMYK (Cyan, Magenta, Yellow, blacK) color model is widely used in printed media – just as the RGB (Red, Green, Blue) model used for on-screen colors. Below is a simple RGB-to-CMYK color converter function. Try it now – input the RGB values (in the range 0 to 255) and click Convert to CMYK:

R: G: B: C: M: Y: K:
Here is the source code of the RGB-to-CMYK converter function.
function rgb2cmyk (r,g,b) {
 computedC = 0;
 computedM = 0;
 computedY = 0;
 computedK = 0;

 // trim leading/trailing spaces from input RGB values
 var r = parseInt( (''+r).replace(/^\s|\s$/g,'') ); 
 var g = parseInt( (''+g).replace(/^\s|\s$/g,'') ); 
 var b = parseInt( (''+b).replace(/^\s|\s$/g,'') ); 

 if (r==null || isNaN(r) || g==null || isNaN(g) || b==null || isNaN(b)) {
   alert ('Please enter numeric RGB values!');
   return;
 }
 if (r<0 || g<0 || b<0 || r>255 || g>255 || b>255) {
   alert ('RGB values must be in the range 0 to 255.');
   return;
 }

 // BLACK
 if (r==0 && g==0 && b==0) {
  computedK = 1;
  return [0,0,0,1];
 }

 computedC = 1 - (r/255);
 computedM = 1 - (g/255);
 computedY = 1 - (b/255);

 var minCMY = Math.min(computedC,Math.min(computedM,computedY));

 computedC = (computedC - minCMY) / (1 - minCMY) ;
 computedM = (computedM - minCMY) / (1 - minCMY) ;
 computedY = (computedY - minCMY) / (1 - minCMY) ;
 computedK = minCMY;

 return [computedC,computedM,computedY,computedK];
}

See also other color converters:

  • Hex to CMYK
  • Hex to RGB
  • RGB to Hex

    Copyright © 1999-2008, JavaScripter.net.