RGB to HSB Color - CSharp System.Drawing

CSharp examples for System.Drawing:Color RGB

Description

RGB to HSB Color

Demo Code


using System.Drawing;
using System.Text;
using System.Collections.Generic;
using System;/*ww w  .  ja va  2 s  .com*/

public class Main{
        public static void RGB2HSB(int r, int g, int b, out int hue, out int sat, out int bri)
        {
            float fHue, fSat, fBri;

            RGB2HSB(r, g, b, out fHue, out fSat, out fBri);

            hue = (int)((fHue / 360.0f) * 240 + 0.5);
            sat = (int)(fSat * 241 + 0.5);
            bri = (int)(fBri * 241 + 0.5);

            if (hue > 239)
            {
                hue = 239;
            }

            if (sat > 240)
            {
                sat = 240;
            }

            if (bri > 240)
            {
                bri = 240;
            }
        }
        public static void RGB2HSB(int r, int g, int b, out float hue, out float sat, out float bri)
        {
            int minval = Math.Min(r, Math.Min(g, b));
            int maxval = Math.Max(r, Math.Max(g, b));

            //bri 
            bri = (float)(maxval + minval) / 510;

            //sat 
            if (maxval == minval)
            {
                sat = 0.0f;
            }
            else
            {
                int sum = maxval + minval;

                if (sum > 255)
                {
                    sum = 510 - sum;
                }

                sat = (float)(maxval - minval) / sum;
            }

            //hue 
            if (maxval == minval)
            {
                hue = 0.0f;
            }
            else
            {
                float diff = (float)(maxval - minval);
                float rnorm = (maxval - r) / diff;
                float gnorm = (maxval - g) / diff;
                float bnorm = (maxval - b) / diff;

                hue = 0.0f;

                if (r == maxval)
                {
                    hue = 60.0f * (6.0f + bnorm - gnorm);
                }

                if (g == maxval)
                {
                    hue = 60.0f * (2.0f + rnorm - bnorm);
                }

                if (b == maxval)
                {
                    hue = 60.0f * (4.0f + gnorm - rnorm);
                }

                if (hue > 360.0f)
                {
                    hue = hue - 360.0f;
                }
            }
        }

        public static void RGB2HSB(Color cor, out int hue, out int sat, out int bri)
        {
            RGB2HSB(cor.R, cor.G, cor.B, out hue, out sat, out bri);
        }
}

Related Tutorials