开发者

How to convert RGB int values to string color

开发者 https://www.devze.com 2023-02-20 19:11 出处:网络
Can anyone tell me how to convert three int vales r, g, b开发者_JAVA技巧 into a string color(hexa value) in C#int red = 255;

Can anyone tell me how to convert three int vales r, g, b开发者_JAVA技巧 into a string color(hexa value) in C#


int red = 255;
int green = 255;
int blue = 255;

string theHexColor = "#" + red.ToString("X2") + green.ToString("X2") + blue.ToString("X2");


Try this

 string s = Color.FromArgb(255, 143, 143, 143).Name;


Rgb to Hex:

string hexColor = string.Format("0x{0:X8}", Color.FromArgb(r, g, b).ToArgb());

Hex to Rgb:

int rgbColor = int.Parse("FF", System.Globalization.NumberStyles.AllowHexSpecifier);


Please find the following extension method:

public static class ColorExtensions
{
    public static string ToRgb(this int argb)
    {
        var r = ((argb >> 16) & 0xff);
        var g = ((argb >> 8) & 0xff);
        var b = (argb & 0xff);

        return string.Format("{0:X2}{1:X2}{2:X2}", r, g, b);
    }
}

and here you are the usage:

        int colorBlack = 0x000000;
        int colorWhite = 0xffffff;

        Assert.That(colorBlack.ToRgb(), Is.EqualTo("000000"));
        Assert.That(colorWhite.ToRgb(), Is.EqualTo("FFFFFF"));


Resolving this issue for a PowerPoint shape object's Fill.ForeColor.RGB member, I find the RGB values are actually BGR (blue, green, red), so the solution for a C# PowerPoint addin, converting Fill.ForeColor.RGB to a string is:

string strColor = "";
var b = ((shpTemp.Fill.ForeColor.RGB >> 16) & 0xff);
var g = ((shpTemp.Fill.ForeColor.RGB >> 8) & 0xff);
var r = (shpTemp.Fill.ForeColor.RGB & 0xff);

strColor = string.Format("{0:X2}{1:X2}{2:X2}", r, g, b);


What I did was the following:

    int reducedRed = getRed(long color)/128; // this gives you a number 1 or 0. 
    int reducedGreen = getGreen(long color)/128; // same thing for the green value; 
    int reducedBlue = getBlue(long color)/128; //same thing for blue
    int reducedColor = reducedBlue + reducedGreen*2 + reducedRed*4 ;
    // reduced Color is a number between 0 -7 

Once you have the reducedColor then perform a switch between 0 to 7.

    switch(reducedColor){
       case 0: return "000000";      // corresponds to Black
       case 1: return “0000FF";         // corresponds to Blue
       case 2: return "00FF00";       // corresponds to Green
       case 3: return "00FFFF";        // corresponds to Cyan 
       case 4: return “FF0000";          // corresponds to Red
       case 5: return "FF00FF";       //corresponds to Purple
       case 6: return "FFFF00";     //corresponds to Yellow
       case 7: return  “FFFFFF";       //corresponds to White
    }

O

0

精彩评论

暂无评论...
验证码 换一张
取 消