Color Conversions

The procedures to be used for converting color values from one model to another are illustrated below. Click on the conversion titles below to toggle the display for that conversion. You can simply copy and paste the JavaScript functions into your own code without any modification. If you are unfamiliar with the JavaScript conditional operator, ?, you will find a brief tutorial here.

255 (R)
0 (G)
0 (B)
0% (C)
100% (M)
100% (Y)
0° (H)
100% (S)
50% (L)
#FF0000

All conversions are approximate.

RGB → CMY
C = 1 - (R/255)   M = 1 - (G/255)   Y = 1 - (B/255)
CMY → RGB
R = (1 - C)*255   G = (1 - M)*255   B = (1 - Y)*255
CMY → CMYK
function CMY_2_CMYK(C,M,Y)
{
 var K = (C < 1)?C:1;
 K = (M < K)?M:K;
 K = (Y < K)?Y:K;
 if (K == 1) 
 {
  C = 0;
  M = 0;
  K = 0;
  //using pure black so set C, M and Y to zero
 } else
 {
  var KMinus = 1 - K;
  C = (C - K)/KMinus;
  M = (M - K)/KMinus;
  Y = (Y - K)/KMinus;
 }
 return [C,M,Y,K]//returns C,M,Y and K as an array
}
CMYK → CMY
C = C*(1 - K) + K     M = M*(1 - K) + K     Y = Y*(1 - K) + K

K can only have one of two values - zero or one. The only justification for CMYK is the quality and economy of black it delivers.
RGB → HSL
function RGB_2_HSL(R,G,B)
{
 var normR = R/255;
 var normG = G/255;
 var normB = B/255;
 var minRGB = Math.min(normR,Math.min(normG,normB));
 var maxRGB = Math.max(normR,Math.max(normG,normB));
 
 var spanRGB = maxRGB - minRGB;
 var H,S,L = (maxRGB + minRGB)/2;
 if (spanRGB == 0) return [0,0,L*100];
 
 S = (L < 0.5)?spanRGB/(maxRGB + minRGB):spanRGB/(2 - maxRGB - minRGB);
 var halfSpan = spanRGB/2;
 var spanR = ((maxRGB - normR)/6 + halfSpan)/spanRGB;
 var spanG = ((maxRGB - normG)/6 + halfSpan)/spanRGB;
 var spanB = ((maxRGB - normB)/6 + halfSpan)/spanRGB;

 if (normR == maxRGB) H = spanB - spanG
 else if (normG == maxRGB) H = 1/3 + spanR - spanB  
 else if (normB == maxRGB) H = 2/3 + spanG - spanR;
 
 H+=(H < 0)?1:0;  
 H-=(H > 1)?1:0;  
 return [H*360,S*100,L*100];
}
HSL → RGB
function Hue_2_RGB(m1,m2,h)
{
h+=(h < 0)?1:0;
h-=(h > 1)?1:0;
 if (h*6 < 1) return 6*h*(m2 - m1) + m1;
 if (h*2 < 1) return m2;
 if (h*3 < 2) return 6*(m2 - m1)*(2/3 - h) + m1;
 return m1;
}

function HSL_2_RGB(H,S,L)
{
 var H = H/360;S = S/100;L = L/100;
 
 if (S == 0) 
 {
  L = L*255;
  return [L,L,L];
 }
 
 var m2 = (L < 0.5)?L*(1 + S):L + S - L*S;
 var m1 = L*2 - m2;  
 var R = 255*Hue_2_RGB(m1,m2,H + 1/3);
 var G = 255*Hue_2_RGB(m1,m2,H);
 var B = 255*Hue_2_RGB(m1,m2,H - 1/3);
 return [R,G,B];
}
Jump To...

Colophon