Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an Integer to Red, Green, and Blue values

Tags:

c#

integer

rgb

I'm converting an RGB value to a single integer with the following:

public static int RGBtoInt(int red, int greed, int blue)
{
    return blue + green + (green * 255) + (red * 65536);
}

but struggling to write an inverse method taking in an integer and returning the single RGB components.

Something of thematic nature with:

public static Vector3 IntToRgb(int value)
{
    // calculations...
    return new Vector3(red, green, blue); 
}

The Color.FromArgb(int) method isn't creating the RGB colour I need.

The RGBtoInt function above matches the RGB integer values returned by OpenGL and I am looking for a reverse method. It's the same conversion method used here.

like image 347
livin_amuk Avatar asked Apr 26 '16 11:04

livin_amuk


2 Answers

The conversion can be done as follows.

public static Vector3 IntToRgb(int value)
{
    var red =   ( value >>  0 ) & 255;
    var green = ( value >>  8 ) & 255;
    var blue =  ( value >> 16 ) & 255;
    return new Vector3(red, green, blue); 
}

To my understanding, the initial conversion should be done as follows.

public static int RGBtoInt(int r, int g, int b)
{
    return ( r << 0 ) | ( g << 8 ) | ( b << 16 );
}
like image 51
Codor Avatar answered Sep 28 '22 00:09

Codor


Try this Color c = Color.FromArgb(someInt); and then use c.R, c.G and c.B for Red, Green and Blue values respectively

like image 26
Hamletkrita Avatar answered Sep 28 '22 01:09

Hamletkrita