Algorithm to Switch Between RGB and HSB Color Values

后端 未结 6 650
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 08:18

I read the article Algorithm to Switch Between RGB and HSB Color Values

Type RGBColor
     Red As Byte
     Green As Byte
     Blue As Byte
End Type

Type HS         


        
6条回答
  •  無奈伤痛
    2020-12-06 08:34

    Solution

    You can calculate the Brightness component quite simply as it's the max of R, G, and B (reference: formula for RGB to HSV from the Rochester Institute of Technology). You can scale it however you like by dividing by 255 and multiplying by the scale. This is the same as done in your existing code:

    maxRGB = Max(Max(rgb.Red, rgb.Green), rgb.Blue)
    b = maxRGB    
    ...    
    RGBToHSB.Brightness = b * 100 / 255
    

    So, in the end you can use the built-in .Net functions and just calculate your brightness. Full code would be (excluding your types):

    Function RGBToHSB(rgb As RGBColor) As HSBColor
      Dim maxRGB As Double
      maxRGB = Max(Max(rgb.Red, rgb.Green), rgb.Blue)
    
      Dim c As Color = Color.FromArgb(rgb.Red, rgb.Green, rgb.Blue)
      RGBToHSB.Hue = c.GetHue()
      RGBToHSB.Saturation = c.GetSaturation() * 100
      RGBToHSB.Brightness = maxRGB * 100 / 255
    End Function
    

    A bit about HSB (same as HSV)

    From Darel Rex Finley:

    In the HSV (also called HSB) system, the brightness of a color is its V component. That component is defined simply as the maximum value of any of the three RGB components of the color — the other two RGB components are ignored when determining V.

    According the the Microsoft Documentation for Color.GetBrightness:

    Gets the hue-saturation-brightness (HSB) brightness value for this Color structure.

    I have found some references saying the MSDN uses HSB when it means HSL like this one from MSDN blogs (see the comments). A quick test proves this to be true (in C#):

    // Define a color which gives different HSL and HSB value
    Color c = Color.FromArgb(255, 0, 0);
    // Get the brightness, scale it from 0.0 - 1.0 up to 0 - 255
    int bright = (int)(c.GetBrightness() * 255.00);
    // Output it
    Console.WriteLine(bright.ToString());
    

    This results in a value of 127, which is clearly HSL. If it was HSB the value should be the max of R G and B (i.e. 255).

提交回复
热议问题