How to Write and Read a Color in C#


Transforming a color in hexa representation using following function:

private string WriteHexString(byte aobjColR, byte aobjColG, byte aobjColB)
{
string
strRet;
byte
[] btR = {aobjColR};
string
strR = ToHexString(btR);
strRet = strR;
byte[] btG = {this
.colorDialog1.Color.G};
string
strG = ToHexString(btG);
strRet += strG;
byte[] btB = {this
.colorDialog1.Color.B};
string
strB = ToHexString(btB);
strRet += strB;
return
strRet;
}
//WriteHexString

This function transform a Color (defined as Color.R, Color.G, Color.B) in hexa representation (as string) and use following helper functions:

private static string ToHexString(byte[] bytes)
{
char[] chars = new char
[bytes.Length * 2];
for (int
i = 0; i < bytes.Length; i++)
{
int
b = bytes[i];
chars[i * 2] = hexDigits[b >> 4];
chars[i * 2 + 1] = hexDigits[b & 0xF];
}
return new string
(chars);
}
//ToHexString
 
static char
[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

To transform "hexa" representation back
in
color we can use following function:

private Color GetColor(string astrHexString)
{
string
strR;
string
strG;
string
strB;
string
strRL;
string
strRR;
string
strGL;
string
strGR;
string
strBL;
string
strBR;
int
iR;
int
iG;
int
iB;
int
iRL;
int
iRR;
int
iGL;
int
iGR;
int
iBL;
int
iBR;
Color c;
strR = astrHexString.Substring(0,2);
strG = astrHexString.Substring(2,2);
strB = astrHexString.Substring(4,2);
strRL = strR.Substring(0,1);
strRR = strR.Substring(1,1);
strGL = strG.Substring(0,1);
strGR = strG.Substring(1,1);
strBL = strB.Substring(0,1);
strBR = strB.Substring(1,1);
iRL = GetIntFromHex(strRL);
iRR = GetIntFromHex(strRR);
iGL = GetIntFromHex(strGL);
iGR = GetIntFromHex(strGR);
iBL = GetIntFromHex(strBL);
iBR = GetIntFromHex(strBR);
iR = 16 * iRL + iRR;
iG = 16 * iGL + iGR;
iB = 16 * iBL + iBR;
c = Color.FromArgb(iR, iG, iB);
return
c;
}
//GetColour

and helper function:

private int GetIntFromHex(string strHex)
{
switch
(strHex)
{
case
("A"):
{
return
10;
}
case
("B"):
{
return
11;
}
case
("C"):
{
return
12;
}
case
("D"):
{
return
13;
}
case
("E"):
{
return
14;
}
case
("F"):
{
return
15;
}
default
:
{
return int
.Parse(strHex);
}
}
}
//GetIntFromHex 

The complete code is in zip file.

Up Next
    Ebook Download
    View all
    Learn
    View all