Hex-to-CMYK Conversion

JavaScript FAQ | JavaScript Colors FAQ  

Question: How do I convert a hex color string (e.g. "FFFFCC") to CMYK values of the same color?

Answer: The CMYK (Cyan, Magenta, Yellow, blacK) color model is widely used in printed media. Below is a simple hex-to-CMYK color converter function. It uses, as its initial step, the hex-to-RGB conversion. Try it yourself:

C: M: Y: K:
Here is the source code of the hex-to-CMYK converter function:
function hexToCMYK (hex) {
 var computedC = 0;
 var computedM = 0;
 var computedY = 0;
 var computedK = 0;

 hex = (hex.charAt(0)=="#") ? hex.substring(1,7) : hex;

 if (hex.length != 6) {
  alert ('Invalid length of the input hex value!');   
  return; 
 }
 if (/[0-9a-f]{6}/i.test(hex) != true) {
  alert ('Invalid digits in the input hex value!');
  return; 
 }

 var r = parseInt(hex.substring(0,2),16); 
 var g = parseInt(hex.substring(2,4),16); 
 var b = parseInt(hex.substring(4,6),16); 

 // 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
  • Hex to RGB color converter
  • RGB to Hex color converter
  • RGB 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.