views:

918

answers:

2

Using C# I was trying to develop the following two. The way I am doing it may have some problem and need your kind advice. In addition, I dont know whether there is any existing method to do the same.

private static String HexConverter(System.Drawing.Color c)
{
    String rtn = String.Empty;
    try
    {
        rtn = "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
    }
    catch (Exception ex)
    {
        //doing nothing
    }

    return rtn;
}

private static String RGBConverter(System.Drawing.Color c)
{
    String rtn = String.Empty;
    try
    {
        rtn = "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
    }
    catch (Exception ex)
    {
        //doing nothing
    }

    return rtn;
}

Thanks.

+2  A: 

You could keep it simple and use the native colour translator:

Color red = ColorTranslator.FromHtml("#FF0000");
string redHex = ColorTranslator.ToHtml(red);

Then break the three colour pairs into decimal:

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
Troy Hunt
But if I do this way, Color red = System.Drawing.Color.Red; string redHex = ColorTranslator.ToHtml(red);it does not provide the Hex Value.
Hoque
Certainly should do, I tested that code specifically and got #"FF0000". What are you getting? You might also like to refer to the MSDN reference: http://msdn.microsoft.com/en-us/library/system.drawing.colortranslator.tohtml.aspx
Troy Hunt
Try with Color red = System.Drawing.Color.Red; --> it does not provide #FF0000.
Hoque
So using exactly the first code block I provided, what is the value of redHex? I think something on your side is missing.
Troy Hunt
The code you have provided works but when I change the first line of your code to : Color red = System.Drawing.Color.Red; --> Then it does not give the hex code. It gives "Red" as an output.
Hoque
A: 

I'm failing to see the problem here. The code looks good to me. The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and c.R.ToString(), c.G.ToString(), and c.B.ToString() can't actually fail (the only way I can see them failing is with a NullReferenceException, and none of them can actually be null). You could clean the whole thing up using the following:

private static String HexConverter(System.Drawing.Color c)
{
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

private static String RGBConverter(System.Drawing.Color c)
{
    return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")";
}
Ari Roth