RGB To HSL

This algorithm converts RGB color model to HSL color model.



									Public Structure RGB
	Private _r As Byte
	Private _g As Byte
	Private _b As Byte

	Public Sub New(r As Byte, g As Byte, b As Byte)
		Me._r = r
		Me._g = g
		Me._b = b
	End Sub

	Public Property R() As Byte
		Get
			Return Me._r
		End Get
		Set(value As Byte)
			Me._r = value
		End Set
	End Property

	Public Property G() As Byte
		Get
			Return Me._g
		End Get
		Set(value As Byte)
			Me._g = value
		End Set
	End Property

	Public Property B() As Byte
		Get
			Return Me._b
		End Get
		Set(value As Byte)
			Me._b = value
		End Set
	End Property

	Public Overloads Function Equals(rgb As RGB) As Boolean
		Return (Me.R = rgb.R) AndAlso (Me.G = rgb.G) AndAlso (Me.B = rgb.B)
	End Function
End Structure

Public Structure HSL
	Private _h As Integer
	Private _s As Single
	Private _l As Single

	Public Sub New(h As Integer, s As Single, l As Single)
		Me._h = h
		Me._s = s
		Me._l = l
	End Sub

	Public Property H() As Integer
		Get
			Return Me._h
		End Get
		Set(value As Integer)
			Me._h = value
		End Set
	End Property

	Public Property S() As Single
		Get
			Return Me._s
		End Get
		Set(value As Single)
			Me._s = value
		End Set
	End Property

	Public Property L() As Single
		Get
			Return Me._l
		End Get
		Set(value As Single)
			Me._l = value
		End Set
	End Property

	Public Overloads Function Equals(hsl As HSL) As Boolean
		Return (Me.H = hsl.H) AndAlso (Me.S = hsl.S) AndAlso (Me.L = hsl.L)
	End Function
End Structure

Public Shared Function RGBToHSL(rgb As RGB) As HSL
	Dim hsl As New HSL()

	Dim r As Single = (rgb.R / 255.0F)
	Dim g As Single = (rgb.G / 255.0F)
	Dim b As Single = (rgb.B / 255.0F)

	Dim min As Single = Math.Min(Math.Min(r, g), b)
	Dim max As Single = Math.Max(Math.Max(r, g), b)
	Dim delta As Single = max - min

	hsl.L = (max + min) / 2

	If delta = 0 Then
		hsl.H = 0
		hsl.S = 0.0F
	Else
		hsl.S = If((hsl.L <= 0.5), (delta / (max + min)), (delta / (2 - max - min)))

		Dim hue As Single

		If r = max Then
			hue = ((g - b) / 6) / delta
		ElseIf g = max Then
			hue = (1.0F / 3) + ((b - r) / 6) / delta
		Else
			hue = (2.0F / 3) + ((r - g) / 6) / delta
		End If

		If hue < 0 Then
			hue += 1
		End If
		If hue > 1 Then
			hue -= 1
		End If

		hsl.H = CInt(Math.Truncate(hue * 360))
	End If

	Return hsl
End Function
								


Example

									Dim data As New RGB(82, 0, 87)
Dim value = RGBToHSL(data)
								


Output

									H: 296
S: 1
L: 0.17058824F