Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert System.Drawing.Color to RGB and Hex Value

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.

like image 861
Nazmul Avatar asked Mar 07 '10 06:03

Nazmul


People also ask

Are RGB and hex the same?

There is no informational difference between RGB and HEX colors; they are simply different ways of communicating the same thing – a red, green, and blue color value. HEX, along with its sister RGB, is one of the color languages used in coding, such as CSS. HEX is a numeric character based reference of RGB numbers.


1 Answers

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() + ")"; } 
like image 60
Ari Roth Avatar answered Sep 30 '22 09:09

Ari Roth