Try it yourself with our free Color Picker tool — runs entirely in your browser, no signup needed.

How to Convert colors (HEX/RGB/HSL) in C#

How to convert colors (HEX/RGB/HSL) in C#

Converting colors between different formats is a common task in many applications, such as graphic design, web development, and game development. In C#, converting colors between HEX, RGB, and HSL formats can be achieved using the System.Drawing namespace. In this article, we will explore how to perform these conversions, handling edge cases, and provide performance tips.

Quick Example

using System.Drawing;

public class ColorConverter
{
    public static Color HexToRgb(string hex)
    {
        hex = hex.TrimStart('#');
        return ColorTranslator.FromHtml("#" + hex);
    }

    public static string RgbToHex(Color rgb)
    {
        return "#" + rgb.R.ToString("X2") + rgb.G.ToString("X2") + rgb.B.ToString("X2");
    }

    public static HslColor RgbToHsl(Color rgb)
    {
        var hsl = new HslColor();
        hsl.R = rgb.R / 255.0;
        hsl.G = rgb.G / 255.0;
        hsl.B = rgb.B / 255.0;
        hsl.H = GetHue(hsl.R, hsl.G, hsl.B);
        hsl.S = GetSaturation(hsl.R, hsl.G, hsl.B);
        hsl.L = GetLightness(hsl.R, hsl.G, hsl.B);
        return hsl;
    }

    // implementation of GetHue, GetSaturation, and GetLightness methods
}

This example provides a basic implementation of color conversion methods. You can use these methods to convert colors between HEX, RGB, and HSL formats.

Step-by-Step Breakdown

Let's break down the code line by line:

  1. using System.Drawing; - We import the System.Drawing namespace, which provides the Color struct and other related classes.
  2. public static Color HexToRgb(string hex) - This method converts a HEX color to an RGB color.
  3. hex = hex.TrimStart('#'); - We remove the leading '#' character from the HEX string.
  4. return ColorTranslator.FromHtml("#" + hex); - We use the ColorTranslator class to convert the HEX string to an RGB color.
  5. public static string RgbToHex(Color rgb) - This method converts an RGB color to a HEX color.
  6. return "#" + rgb.R.ToString("X2") + rgb.G.ToString("X2") + rgb.B.ToString("X2"); - We convert the RGB values to HEX strings using the ToString method with the "X2" format specifier.
  7. public static HslColor RgbToHsl(Color rgb) - This method converts an RGB color to an HSL color.
  8. var hsl = new HslColor(); - We create a new HslColor object to store the converted values.
  9. hsl.R = rgb.R / 255.0; - We convert the RGB values to normalized values between 0 and 1.
  10. hsl.H = GetHue(hsl.R, hsl.G, hsl.B); - We calculate the hue value using the GetHue method.
  11. hsl.S = GetSaturation(hsl.R, hsl.G, hsl.B); - We calculate the saturation value using the GetSaturation method.
  12. hsl.L = GetLightness(hsl.R, hsl.G, hsl.B); - We calculate the lightness value using the GetLightness method.

Handling Edge Cases

Empty/null input

public static Color HexToRgb(string hex)
{
    if (string.IsNullOrEmpty(hex))
    {
        throw new ArgumentException("HEX string cannot be null or empty");
    }
    // ...
}

We add a null check to ensure that the input HEX string is not null or empty.

Invalid input

public static Color HexToRgb(string hex)
{
    if (!hex.StartsWith("#"))
    {
        throw new ArgumentException("HEX string must start with '#'");
    }
    // ...
}

We add a check to ensure that the input HEX string starts with the '#' character.

Large input

public static Color[] HexToRgb(string[] hexColors)
{
    var rgbColors = new Color[hexColors.Length];
    for (int i = 0; i < hexColors.Length; i++)
    {
        rgbColors[i] = HexToRgb(hexColors[i]);
    }
    return rgbColors;
}

We create a method that takes an array of HEX strings and returns an array of RGB colors.

Unicode/special characters

public static Color HexToRgb(string hex)
{
    hex = hex.Normalize(NormalizationForm.FormD);
    // ...
}

We use the Normalize method to normalize the input HEX string to the Unicode Form D format.

Common Mistakes

Mistake 1: Not trimming the '#' character

// wrong code
return ColorTranslator.FromHtml(hex);

// corrected code
return ColorTranslator.FromHtml("#" + hex.TrimStart('#'));

Not trimming the '#' character can cause the ColorTranslator class to throw an exception.

Mistake 2: Not handling null/empty input

// wrong code
return ColorTranslator.FromHtml(hex);

// corrected code
if (string.IsNullOrEmpty(hex))
{
    throw new ArgumentException("HEX string cannot be null or empty");
}
return ColorTranslator.FromHtml("#" + hex.TrimStart('#'));

Not handling null/empty input can cause a NullReferenceException to be thrown.

Mistake 3: Not checking for invalid input

// wrong code
return ColorTranslator.FromHtml(hex);

// corrected code
if (!hex.StartsWith("#"))
{
    throw new ArgumentException("HEX string must start with '#'");
}
return ColorTranslator.FromHtml("#" + hex.TrimStart('#'));

Not checking for invalid input can cause the ColorTranslator class to throw an exception.

Performance Tips

  1. Use the ColorTranslator class to convert between HEX and RGB colors, as it is optimized for performance.
  2. Use the Normalize method to normalize the input HEX string to the Unicode Form D format, which can improve performance when working with Unicode characters.
  3. Use arrays to convert multiple colors at once, which can improve performance when working with large datasets.

FAQ

Q: What is the difference between RGB and HSL color models?

A: RGB (Red, Green, Blue) is an additive color model, while HSL (Hue, Saturation, Lightness) is a subtractive color model.

Q: How do I convert an HSL color to an RGB color?

A: You can use the HslColor struct and the GetRgb method to convert an HSL color to an RGB color.

Q: What is the purpose of the Normalize method?

A: The Normalize method is used to normalize the input HEX string to the Unicode Form D format, which can improve performance when working with Unicode characters.

Q: Can I use this code in a production environment?

A: Yes, this code is designed to be used in a production environment and is optimized for performance.

Q: How do I handle errors when converting colors?

A: You can use try-catch blocks to handle errors when converting colors, and throw exceptions when invalid input is encountered.

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp