vic
vic

Reputation: 227

How to convert RGBA css color format to hexadecimal format

In my selenium code i need to verify that color code is #192856 for background. but when i get the CSS property of that element it is giving me color in rgba format. Now i need to get values in hex values itself . How can i do that?

quickLinkstab.GetCssValue("background-color")

above is givingm e value of "rgba(25, 40, 86, 1)" which is rgba value. Is there any way i can convert it back to Hex ? or i can get value in Hex itself?

i've also tried below code

 string colorcode = menuColor;
        int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
        Color clr = Color.FromArgb(argb);


        int r = Convert.ToInt16(clr.R);
        int g = Convert.ToInt16(clr.G);
        int b = Convert.ToInt16(clr.B);
        int a = Convert.ToInt16(clr.A);
        string x = string.Format("rgba({0}, {1}, {2}, {3});", r, g, b,a);

but this one is giving me value like , "rgba(25, 40, 86, 0);" . Difference in "a" value. Like my code gives me 0 for "a" but cssvalue is 1.

I'm more looking towards the solution of getting Hex value directly or if not possible then convert rgba to Hex.

Upvotes: 11

Views: 18094

Answers (7)

oudi
oudi

Reputation: 677

using System.Drawing.ColorTranslator

string htmlColor = ColorTranslator.ToHtml(myColor);

using String.Format

//RGB
String.Format("#{0:X2}{1:X2}{2:X2}", colorValue.R,colorValue.G,colorValue.B);
//RGBA
 var strigifiedColor = String. Format("#{0:X2}{1:X2}{2:X2}{3:X2}", colorValue.R, colorValue.G, colorValue.B, colorValue.A);

Extenstion

public static class ColorExtension
{
    public static string HexFormat(this Color colorValue)
    {
        return String.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", colorValue.A, colorValue.R, colorValue.G, colorValue.B);
    }
}

Upvotes: 3

Mehmet Erdoğdu
Mehmet Erdoğdu

Reputation: 500

Two way convert. I developed and tested.

public static string RgbaToHex(string value)
{
    if (string.IsNullOrEmpty(value))
        return null;
    Color color;
    value = value.Trim();
    if (value.StartsWith("#"))
        color = ColorTranslator.FromHtml(value);
    else
    {
        if (!value.StartsWith("rgba"))
            throw new FormatException("Not rgba string");
        var left = value.IndexOf('(');
        var right = value.IndexOf(')');
        if (left < 0 || right < 0)
            throw new FormatException("rgba format error");
        var noBrackets = value.Substring(left + 1, right - left - 1);
        var parts = noBrackets.Split(',');
        var r = int.Parse(parts[0], CultureInfo.InvariantCulture);
        var g = int.Parse(parts[1], CultureInfo.InvariantCulture);
        var b = int.Parse(parts[2], CultureInfo.InvariantCulture);
        switch (parts.Length)
        {
            case 3:
                color = Color.FromArgb(r, g, b);
                break;
            case 4:
            {
                var a = float.Parse(parts[3], CultureInfo.InvariantCulture);
                color = Color.FromArgb((int)(a * 255), r, g, b);
                break;
            }
            default:
                throw new FormatException("Not rgba string");
        }
    }

    return "#" + color.A.ToString("X2") + color.R.ToString("X2") + color.G.ToString("X2") + color.B.ToString("X2");
}

public static string HexToRgba(string value)
{
    if (string.IsNullOrEmpty(value))
        return null;
    var argb = int.Parse(value.Replace("#", ""), NumberStyles.HexNumber);
    var clr = Color.FromArgb(argb);
    int r = Convert.ToInt16(clr.R);
    int g = Convert.ToInt16(clr.G);
    int b = Convert.ToInt16(clr.B);
    int a = Convert.ToInt16(clr.A);
    var trans = Math.Round((double)a / 255, 2).ToString("N2").Replace(",", ".");
    return $"rgba({r}, {g}, {b}, {trans})";
}

Upvotes: 0

bryan valdellon
bryan valdellon

Reputation: 9

There is an available Selenium library for Color:

import org.openqa.selenium.support.Color;

String rgba = "rgba(1,1,1,1)";
Color color = Color.fromString(rgba);
System.out.println("hex value = " + color.asHex());

Upvotes: 0

Etherman
Etherman

Reputation: 1867

I have expanded on Thomas's answer to cover the #RGBA/#RRGGBBAA formats.

You may want to handle errors differently, I prefer to just return Color.Empty if the input cannot be parsed.

(adding unit tests to Typescript led to looking into some C# code, which led to the discovery that ColorTranslator is completely ignorant of alpha values - don't assume anything, test everything!)

public static ColorUtils
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "ColorTranslator throws System.Exception")]
    public static Color HtmlToColor(string htmlColor)
    {
        Guard.ArgumentIsNotNull(htmlColor, nameof(htmlColor));

        var htmlLowerCase = htmlColor.ToLower().Trim();

        try
        {
            if (htmlLowerCase.StartsWith("rgb"))
            {
                return ArgbToColor(htmlLowerCase);
            }
            else if (htmlLowerCase.StartsWith("#"))
            {
                return HexToColor(htmlLowerCase);
            }
            else
            {
                // Fallback to ColorTranslator for named colors, e.g. "Black", "White" etc.
                return ColorTranslator.FromHtml(htmlLowerCase);
            }
        }
        catch
        {
            // ColorTranslator throws System.Exception, don't really care what the actual error is.
        }

        return Color.Empty;
    }

    private static Color HexToColor(string htmlLowerCase)
    {
        var len = htmlLowerCase.Length;

        // #RGB
        if (len == 4)
        {
            var r = Convert.ToInt32(htmlLowerCase.Substring(1, 1), 16);
            var g = Convert.ToInt32(htmlLowerCase.Substring(2, 1), 16);
            var b = Convert.ToInt32(htmlLowerCase.Substring(3, 1), 16);

            return Color.FromArgb(r + (r * 16), g + (g * 16), b + (b * 16));
        }

        // #RGBA
        else if (len == 5)
        {
            var r = Convert.ToInt32(htmlLowerCase.Substring(1, 1), 16);
            var g = Convert.ToInt32(htmlLowerCase.Substring(2, 1), 16);
            var b = Convert.ToInt32(htmlLowerCase.Substring(3, 1), 16);
            var a = Convert.ToInt32(htmlLowerCase.Substring(4, 1), 16);

            return Color.FromArgb(a + (a * 16), r + (r * 16), g + (g * 16), b + (b * 16));
        }

        // #RRGGBB
        else if (len == 7)
        {
            return Color.FromArgb(
                Convert.ToInt32(htmlLowerCase.Substring(1, 2), 16),
                Convert.ToInt32(htmlLowerCase.Substring(3, 2), 16),
                Convert.ToInt32(htmlLowerCase.Substring(5, 2), 16));
        }

        // #RRGGBBAA
        else if (len == 9)
        {
            return Color.FromArgb(
                Convert.ToInt32(htmlLowerCase.Substring(7, 2), 16),
                Convert.ToInt32(htmlLowerCase.Substring(1, 2), 16),
                Convert.ToInt32(htmlLowerCase.Substring(3, 2), 16),
                Convert.ToInt32(htmlLowerCase.Substring(5, 2), 16));
        }

        return Color.Empty;
    }

    private static Color ArgbToColor(string htmlLowerCase)
    {
        int left = htmlLowerCase.IndexOf('(');
        int right = htmlLowerCase.IndexOf(')');

        if (left < 0 || right < 0)
        {
            return Color.Empty;
        }

        string noBrackets = htmlLowerCase.Substring(left + 1, right - left - 1);

        string[] parts = noBrackets.Split(',');

        int r = int.Parse(parts[0], CultureInfo.InvariantCulture);
        int g = int.Parse(parts[1], CultureInfo.InvariantCulture);
        int b = int.Parse(parts[2], CultureInfo.InvariantCulture);

        if (parts.Length == 3)
        {
            return Color.FromArgb(r, g, b);
        }
        else if (parts.Length == 4)
        {
            float a = float.Parse(parts[3], CultureInfo.InvariantCulture);

            return Color.FromArgb((int)(a * 255), r, g, b);
        }

        return Color.Empty;
    }
}

Tests:

    [TestMethod]
    public void ColorUtils_HtmlToColor()
    {
        Assert.AreEqual(Color.FromArgb(0x11, 0x22, 0x33), ColorUtils.HtmlToColor("#123"), "#123 (without alpha channel)");
        Assert.AreEqual(Color.FromArgb(0x11, 0x22, 0x33), ColorUtils.HtmlToColor("#112233"), "#112233 (without alpha channel)");
        Assert.AreEqual(Color.FromArgb(0x44, 0x11, 0x22, 0x33), ColorUtils.HtmlToColor("#1234"), "#1234 (alpha channel)");
        Assert.AreEqual(Color.FromArgb(0x44, 0x11, 0x22, 0x33), ColorUtils.HtmlToColor("#11223344"), "#11223344 (alpha channel)");
        Assert.AreEqual(Color.FromArgb(127, 11, 22, 33), ColorUtils.HtmlToColor("rgba(11,22,33,0.5)"), "rgba(11,22,33,0.5) (alpha channel)");
        Assert.AreEqual(Color.FromArgb(11, 22, 33), ColorUtils.HtmlToColor("rgb(11,22,33)"), "rgb(11,22,33) (alpha channel)");
        Assert.AreEqual(Color.Red, ColorUtils.HtmlToColor("red"), "red (named color)");
        Assert.AreEqual(Color.White, ColorUtils.HtmlToColor("white"), "white (named color)");
        Assert.AreEqual(Color.Blue, ColorUtils.HtmlToColor("blue"), "blue (named color)");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("invalid"), "invalid");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("#invalid"), "#invalid");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("rgb(invalid)"), "rgb(invalid)");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("rgba(invalid)"), "rgba(invalid)");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("rgba(invalid,invalid)"), "rgba(invalid,invalid)");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("rgb(11,22,333)"), "rgb(11,22,333) (value out of range)");
        Assert.AreEqual(Color.Empty, ColorUtils.HtmlToColor("rgba(11,22,333,0.5)"), "rgb(11,22,333,0.5) (value out of range)");
    }

Upvotes: 1

AGTech
AGTech

Reputation: 1

Below code picks the style attribute from the element and converts the rgb value into hexadecimal format and then compares the value.

string color = GetElement(LocateBy.XPath, "XpathOfTheElement").GetAttribute("style").ToString();
string[] colorvalue1 = color.Split('(');

string[] colorvalue2 = colorvalue1[1].Split(')');

string colorvalue = colorvalue2[0].ToString();
string[] ColorCodeRGBValue = colorvalue.Split(',');
Color myColor = Color.FromArgb(Convert.ToInt32(ColorCodeRGBValue[0]), Convert.ToInt32(ColorCodeRGBValue[1]), Convert.ToInt32(ColorCodeRGBValue[2]));

string hexValue = myColor.R.ToString("X2") + myColor.G.ToString("X2") + myColor.B.ToString("X2");

Assert.AreEqual(hexValue , CsvReader.ColorCode,"Color codes are not equal");

Upvotes: 0

Tomas Kubes
Tomas Kubes

Reputation: 25098

Following code cover hexadecimal format, rgb format and rgba format.

public static class ColorHelper
{
    public static Color ParseColor(string cssColor)
    {
        cssColor = cssColor.Trim();

        if (cssColor.StartsWith("#"))
        {
            return ColorTranslator.FromHtml(cssColor);
        }
        else if (cssColor.StartsWith("rgb")) //rgb or argb
        {
            int left = cssColor.IndexOf('(');
            int right = cssColor.IndexOf(')');

            if (left < 0 || right < 0)
                throw new FormatException("rgba format error");
            string noBrackets = cssColor.Substring(left + 1, right - left - 1);

            string[] parts = noBrackets.Split(',');

            int r = int.Parse(parts[0], CultureInfo.InvariantCulture);
            int g = int.Parse(parts[1], CultureInfo.InvariantCulture);
            int b = int.Parse(parts[2], CultureInfo.InvariantCulture);

            if (parts.Length == 3)
            {
                return Color.FromArgb(r, g, b);
            }
            else if (parts.Length == 4)
            {
                float a = float.Parse(parts[3], CultureInfo.InvariantCulture);
                return Color.FromArgb((int)(a * 255), r, g, b);
            }
        }
        throw new FormatException("Not rgb, rgba or hexa color string");
    }
}

Expected results:

[TestClass]
public class ColorParserTest
{
    [TestMethod]
    public void TestParseColorRGB()
    {
        Color c = ColorHelper.ParseColor("rgb(110,120,130)");

        Assert.AreEqual(110, c.R);
        Assert.AreEqual(120, c.G);
        Assert.AreEqual(130, c.B);
        Assert.AreEqual(255, c.A);
    }

    [TestMethod]
    public void TestParseColorRGBA()
    {
        Color c = ColorHelper.ParseColor("rgba(110,120,130,0.5)");

        Assert.AreEqual(110, c.R);
        Assert.AreEqual(120, c.G);
        Assert.AreEqual(130, c.B);
        Assert.AreEqual(127, c.A);
    }

    [TestMethod]
    public void TestParseColorHexa()
    {
        Color c = ColorHelper.ParseColor("#192856");

        Assert.AreEqual(25, c.R);
        Assert.AreEqual(40, c.G);
        Assert.AreEqual(86, c.B);
        Assert.AreEqual(255, c.A);
    }
}

Upvotes: 17

Andr&#233; Sampaio
Andr&#233; Sampaio

Reputation: 309

This should do the trick.

public static string ConvertRgbaToHex(string rgba)
{
    if (!Regex.IsMatch(rgba, @"rgba\((\d{1,3},\s*){3}(0(\.\d+)?|1)\)"))
            throw new FormatException("rgba string was in a wrong format");

    var matches = Regex.Matches(rgba, @"\d+");
    StringBuilder hexaString = new StringBuilder("#");

    for(int i = 0; i < matches.Count - 1; i++)
    {
        int value = Int32.Parse(matches[i].Value);

        hexaString.Append(value.ToString("X"));
    }

    return hexaString.ToString();
}

Test case:

public class Program
{
    static void Main(string[] args)
    {
        // Output: #192856
        Console.WriteLine(ConvertRgbaToHex("rgba(25, 40, 86, 1)"));

        Console.Read();
    }

    public static string ConvertRgbaToHex(string rgba)
    {
        if (!Regex.IsMatch(rgba, @"rgba\((\d{1,3},\s*){3}(0(\.\d+)?|1)\)"))
                throw new FormatException("rgba string was in a wrong format");

        var matches = Regex.Matches(rgba, @"\d+");
        StringBuilder hexaString = new StringBuilder("#");

        for(int i = 0; i < matches.Count - 1; i++)
        {
            int value = Int32.Parse(matches[i].Value);

            hexaString.Append(value.ToString("X"));
        }

        return hexaString.ToString();
    }
}

Upvotes: 0

Related Questions