Jack
Jack

Reputation: 16724

How to convert color name to the corresponding hexadecimal representation?

For example:

blue 

converts to:

#0000FF

I wrote it as:

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

But I don't know how to get the hexadecimal representation.

Upvotes: 9

Views: 14008

Answers (5)

You can use gplots package:

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

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

Inside gplots package the code for col2hex function is:

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

Upvotes: 1

riwalk
riwalk

Reputation: 14233

Ahmed's answer is close, but based on your comment, I'll just add a little more.

The code that should make this work is:

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.

Upvotes: 3

Jim Balter
Jim Balter

Reputation: 16424

var rgb = color.ToArgb() & 0xFFFFFF; // drop A component
var hexString = String.Format("#{0:X6}", rgb);

or just

var hexString = String.Format("#{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);

Upvotes: 5

Ahmed Masud
Ahmed Masud

Reputation: 22412

{
    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});

// seriously :) this is simple:

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

}

Upvotes: 3

Hand-E-Food
Hand-E-Food

Reputation: 12814

You're half way there. Use .ToArgb to convert it to it's numberical value, then format it as a hex value.

int ColorValue = Color.FromName("blue").ToArgb();
string ColorHex = string.Format("{0:x6}", ColorValue);

Upvotes: 17

Related Questions