RGB→HSL


動作ブラウザ 【 IE:3.0  NN:2.0
Internet Explorer Netscape Navigator DreamPassport iCab
3.0x 4.0x 4.5 5.0x 5.5 2.0x 3.0x 4.0x 4.x 6.0 2 3 2.x
Windows - - -
Macintosh - - -
UNIX - - - - - - - -
Dreamcast - - - - - - - - - - -

ポイント h = s = l = 0; if ( r >= g ) cmax = r; else cmax = g; if ( b > cmax) cmax = b; if ( r <= g ) cmin = r; else cmin = g; if ( b < cmin) cmin = b; l = (cmax + cmin) / 2; c = cmax - cmin; if ( c != 0 ) { if ( l <= 0.5 ) s = c / (cmax + cmin); else s = c / ( 2 - (cmax + cmin)); if ( r == cmax) { h = ( g - b ) / c; }else{ if (g == cmax) { h = 2 + ( b - r ) / c; }else{ if ( b == cmax ) h = 4 + ( r - g ) / c; } } h = h * 60; if ( h < 0 ) h = h + 360; }
説  明 このプログラムは技術評論社「C言語による最新プログラム辞典」第二巻を参考にJavaScript風にアレンジしたものです。
サンプル <html> <head> <title>RGB→HSL</title> <script Language="JavaScript"><!-- function RGBtoHSL() { r = eval(document.myFORM.red.value); g = eval(document.myFORM.green.value); b = eval(document.myFORM.blue.value); h = s = l = 0; if ( r >= g ) cmax = r; else cmax = g; if ( b > cmax) cmax = b; if ( r <= g ) cmin = r; else cmin = g; if ( b < cmin) cmin = b; l = (cmax + cmin) / 2; c = cmax - cmin; if ( c != 0 ) { if ( l <= 0.5 ) s = c / (cmax + cmin); else s = c / ( 2 - (cmax + cmin)); if ( r == cmax) { h = ( g - b ) / c; }else{ if (g == cmax) { h = 2 + ( b - r ) / c; }else{ if ( b == cmax ) h = 4 + ( r - g ) / c; } } h = h * 60; if ( h < 0 ) h = h + 360; } document.myFORM.H.value = h; document.myFORM.S.value = s; document.myFORM.L.value = l; } // --></script> </head> <body> RGB → HSV (Hue, Saturation, Lightness) <form name="myFORM"> 赤(R):<input type="text" name="red"><br> 緑(G):<input type="text" name="green"><br> 青(B):<input type="text" name="blue"><br> <input type="button" onClick="RGBtoHSL()" value="HSLに変換"><br> H:<input type="text" name="H"><br> S:<input type="text" name="S"><br> L:<input type="text" name="L"><br> </form> </body> </html>
補足説明 なし

■サンプルスクリプトを実行する >>実行
■各ブラウザでの動作結果を見る >>View!

写真素材 PIXTA