How to convert a color name to the corresponding hexadecimal representation?

For instance:

blue 

converts to:

#0000FF

I wrote this as:

Color color = Color.FromName("blue");

But I do not know how to get the hexadecimal representation.

+5
source share
5 answers

You're halfway there. Use .ToArgbto convert it to this numeric value and then format it as a hex value.

int ColorValue = Color.FromName("blue").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);
+15
source
var rgb = color.ToArgb() & 0xFFFFFF; // drop A component
var hexString = String.Format("#{0:X6}", rgb);

or simply

var hexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
+4
source
{
    Color color = Color.FromName("blue");
    byte g = color.G;
    byte b = color.B;
    byte r = color.R;
    byte a = color.A;
    string text = String.Format("Color RGBA values: red:{0x}, green: {1}, blue {2}, alpha: {3}", new object[]{r, g, b, a});

//:) :

    string hex = String.Format("#{0:x2}{1:x2}{2:x2}", new object[]{r, g, b}); 

}
+3

, , , .

, :

Color color = Color.FromName("blue");
string myHexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);

Now you can do whatever you want with the string myHexString.

+3
source

You can use the package gplots:

library(gplots)
col2hex("blue")
# [1] "#0000FF"

https://cran.r-project.org/web/packages/gplots/index.html

Inside the package, the gplotscode for the function is col2hex:

col2hex <- function(cname)
{
    colMat <- col2rgb(cname)
    rgb(
        red=colMat[1,]/255,
        green=colMat[2,]/255,
        blue=colMat[3,]/255
    )
}
0
source

All Articles