RGBカラー値をHSLカラー値に変換する

ダーパン
質問: C#でRGBカラー値をHSLカラーに変換したい
C#のプログラムでRGBカラーをHSLカラーに変換したいです。どんなコードを記述すればよいですか?

はじめに

RGBカラーの値をHSLカラー値に変換するコードを紹介します。
メモ
HSLカラーをRGBカラー値に変換するコードはこちらの記事を参照してください。

プログラム例

Webアプリケーションプロジェクトを新規に作成します。

UI

下図のUIを準備します。
RGBカラー値をHSLカラー値に変換する:画像1

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

namespace ColorCalc
{
  public partial class ColorToHls : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button_Convert_Click(object sender, EventArgs e)
    {
      byte R = 0;
      byte G = 0;
      byte B = 0;

      if (RadioButton_RGBInput.Checked == true) {
        try {
          R = Convert.ToByte(TextBox_R.Text);
          G = Convert.ToByte(TextBox_G.Text);
          B = Convert.ToByte(TextBox_B.Text);
        }
        catch (FormatException exc) {

        }
      }
      else {
        try {
          Color inputColorC = ColorTranslator.FromHtml(TextBox_WebColor.Text);
          R = inputColorC.R;
          G = inputColorC.G;
          B = inputColorC.B;
        }
        catch (Exception exc) {
        }
      }

      ColorHSL result = ColorFunction.RgbToHsl(R,G,B);

      TextBox_H.Text = Convert.ToString(result.H);

      TextBox_L.Text = Convert.ToString(result.L);
      double d_lightness_per = result.L * 100;
      TextBox_LPercent.Text = string.Format("{0:##.#}", d_lightness_per);

      TextBox_S.Text = Convert.ToString(result.S);
      double d_saturation_per = result.S * 100;
      TextBox_SPercent.Text = string.Format("{0:##.#}", d_saturation_per);

      string strColor = string.Format("#{0:X2}{1:X2}{2:X2}", R, G, B);
      Label_AddditionalInfo.Text = string.Format("WebColor:{0:s}     RGB値({1:d},{2:d},{3:d})", strColor, R, G, B);
      Literal_ColorBox.Text = string.Format("<div style=\"background-color:{0:s};width:64px;height:64px;float:left;\"></div>", strColor);
    }
  }
}
ColorFunction.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ColorCalc
{
  public class ColorRGB
  {
    public int R { get; set; }
    public int G { get; set; }
    public int B { get; set; }
  }
  public class ColorHSL
  {
    public double H { get; set; }
    public double S { get; set; }
    public double L { get; set; }
  }

  public static class ColorFunction
  {
    public static ColorHSL RgbToHsl(byte r, byte g, byte b)
    {
      // 0〜255 を 0.0〜1.0 に正規化
      double rNorm = r / 255.0;
      double gNorm = g / 255.0;
      double bNorm = b / 255.0;

      double max = Math.Max(rNorm, Math.Max(gNorm, bNorm));
      double min = Math.Min(rNorm, Math.Min(gNorm, bNorm));
      double delta = max - min;

      double h = 0.0;
      double s = 0.0;
      double l = (max + min) / 2.0;

      if (delta != 0) {
        if (max == rNorm) {
          h = ((gNorm - bNorm) / delta) % 6;
        }
        else if (max == gNorm) {
          h = ((bNorm - rNorm) / delta) + 2;
        }
        else // max == bNorm
        {
          h = ((rNorm - gNorm) / delta) + 4;
        }

        h *= 60;
        if (h < 0) h += 360;

        s = delta / (1 - Math.Abs(2 * l - 1));
      }

      return new ColorHSL() { H = h, S = s, L = l };
    }

  }
}

解説

数式の詳細はこちらのページを参照してください。

数式のみを表したものは下図になります。
RGBカラー値をHSLカラー値に変換する:画像2

コード解説

以下のコードにより、入力用のテキストボックスから値を取得します。
      byte R = 0;
      byte G = 0;
      byte B = 0;

      if (RadioButton_RGBInput.Checked == true) {
        try {
          R = Convert.ToByte(TextBox_R.Text);
          G = Convert.ToByte(TextBox_G.Text);
          B = Convert.ToByte(TextBox_B.Text);
        }
        catch (FormatException exc) {

        }
      }
      else {
        try {
          Color inputColorC = ColorTranslator.FromHtml(TextBox_WebColor.Text);
          R = inputColorC.R;
          G = inputColorC.G;
          B = inputColorC.B;
        }
        catch (Exception exc) {
        }
      }

計算結果をテキストボックスに表示するコードです。 テキストボックスに計算結果を表示するだけでなく、Literlコントロールに入力値の色を背景色とする四角の枠を表示します。
      TextBox_H.Text = Convert.ToString(result.H);

      TextBox_L.Text = Convert.ToString(result.L);
      double d_lightness_per = result.L * 100;
      TextBox_LPercent.Text = string.Format("{0:##.#}", d_lightness_per);

      TextBox_S.Text = Convert.ToString(result.S);
      double d_saturation_per = result.S * 100;
      TextBox_SPercent.Text = string.Format("{0:##.#}", d_saturation_per);

      string strColor = string.Format("#{0:X2}{1:X2}{2:X2}", R, G, B);
      Label_AddditionalInfo.Text = string.Format("WebColor:{0:s}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;RGB値({1:d},{2:d},{3:d})", strColor, R, G, B);
      Literal_ColorBox.Text = string.Format("<div style=\"background-color:{0:s};width:64px;height:64px;float:left;\"></div>", strColor);

実行結果

プロジェクトを実行します。Webブラウザが起動し、下図のページが表示されます。
RGBカラー値をHSLカラー値に変換する:画像3

テキストボックスにRGB値を入力します。
RGBカラー値をHSLカラー値に変換する:画像4

変換ボタンをクリックします。HSL値が下部のテキストボックスに表示されます。
RGBカラー値をHSLカラー値に変換する:画像5
AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2012-12-12
Copyright © 1995–2025 iPentec all rights reserverd.