Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert KML hex color to 32 bit ARGB

Tags:

c#

How to convert a hex color into 32 bit ARGB using C#. (without using the built-in color functions)

I tried this but it is not producing the correct color:

string colorcode = "#ff465a82";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);

Thanks Before Hand

Update #1:

Found this but does not work: (Also I am sure it can be done in one line of code)

string colorcode = "ff465a82";

string a = colorcode.Substring(0, 2);
string r = colorcode.Substring(2, 2);
string g = colorcode.Substring(4, 2);
string b = colorcode.Substring(6, 2);

// To integer
int iCol = (a << 24) | (r << 16) | (g << 8) | b;

Solution

Michael Liu, you got this one! Here is the final solution, notice google earth uses ABGR and the standard is ARGB!

// Note Google KML Colors are not in standard format of ARGB
// Google KML Colors are stored as ABGR
public int kmlToARGB(string kmlhexcolor)
{

    kmlhexcolor = kmlhexcolor.TrimStart('#');

    string A = kmlhexcolor.Substring(0, 2);
    string B = kmlhexcolor.Substring(2, 2);
    string G = kmlhexcolor.Substring(4, 2);
    string R = kmlhexcolor.Substring(6, 2);
    int decValue = int.Parse(A + R + G + B, NumberStyles.HexNumber);

    return decValue;

}
like image 834
user3062349 Avatar asked Sep 07 '25 01:09

user3062349


1 Answers

I'm guessing that the drawing API you're using expects color values to be in the format AARRGGBB but your original color code is in the format #AABBGGRR (or vice versa).

Try swapping red and blue before parsing the value:

string colorcode = "#ff465a82";
int argb = Int32.Parse(
    colorcode.Substring(1, 2) + // Alpha
    colorcode.Substring(7, 2) + // Red
    colorcode.Substring(5, 2) + // Green
    colorcode.Substring(3, 2),  // Blue
    NumberStyles.HexNumber);
like image 143
Michael Liu Avatar answered Sep 08 '25 22:09

Michael Liu