RGB-to-CMYK Color Conversion

JavaScript FAQ | JavaScript Colors FAQ  

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 JavaScript source code of the RGB-to-CMYK converter function.
function rgb2cmyk (r,g,b) {
 var computedC = 0;
 var computedM = 0;
 var computedY = 0;
 var computedK = 0;

 //remove spaces from input RGB values, convert to int
 var r = parseInt( (''+r).replace(/\s/g,''),10 ); 
 var g = parseInt( (''+g).replace(/\s/g,''),10 ); 
 var b = parseInt( (''+b).replace(/\s/g,''),10 ); 

 if ( r==null || g==null || b==null ||
     isNaN(r) || isNaN(g)|| 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:
  • JavaScript Colors FAQ
  • RGB to Hex color converter  
  • Hex to RGB color converter
  • Hex to CMYK color converter  
  • RGB to HSV color converter
  • Changing the page background color
  • Changing the color of HTML elements
  • Predefined color names (alphabetical list)
  • Applying another stylesheet to my page
  • Changing the mouse cursor style
  • Copyright © 1999-2012, JavaScripter.net.