How to convert an object of type String "rgba(105, 54, 221, 1)" to Color in Java-Selenium?

Viewed 347

After I get the css value of the color of a WebElement using getCssValue(), I end up with a String with the following format: "rgba(105, 54, 221, 1)". I need to convert it to the Color type-of object, to be able to convert it to hex afterwards, but I get a NumberFormatException for input string: "rgba(105, 54, 221, 1)" when trying to use the Integer.parseInt method.

My code is:

String updatedColorAsString = header.getCssValue("color"); //resulting string is "rgba(105, 54, 221, 1)"
Color updatedColor = new Color(Integer.parseInt(updatedColorAsString));

I am new to Java-Selenium and I have no idea how to work with that String in order to properly convert it to rgba Color, I would really appreciate any help on this :D

1 Answers

There are more options how to get the color.

Be aware of two different Color data types: org.openqa.selenium.support.Color vs java.awt.Color

Color color = Color.fromString(cssColorString); // for selenium Color

or

String[] rgba = cssColorString.replace("rgba(", "").replace(")", "").split(", ");
int r = Integer.parseInt(rgba[0]);
int g = Integer.parseInt(rgba[1]);
int b = Integer.parseInt(rgba[2]);
int a = Integer.parseInt(rgba[3]);
Color color2 = new Color(r, g, b, a); // for any of the two classes

Full code example:

package selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.Color;

public class RaduRaspopa extends WebDriverSetup {

    public static void main(String[] args) {
        
        WebDriver driver = startChromeDriver(); // wrapped driver init
        driver.get("https://www.toolsqa.com/");
        
        WebElement advertisementImage = driver.findElement(By.id("advertisement-image"));
        String cssColorString = advertisementImage.getCssValue("color");

        Color color = Color.fromString(cssColorString);
        System.out.println(color.asHex());
        
        String[] rgba = cssColorString.replace("rgba(", "").replace(")", "").split(", ");
        int r = Integer.parseInt(rgba[0]);
        int g = Integer.parseInt(rgba[1]);
        int b = Integer.parseInt(rgba[2]);
        int a = Integer.parseInt(rgba[3]);
        
        Color color2 = new Color(r, g, b, a);
        System.out.println(color2.asHex());
        
        driver.quit();
    }
    
}

Output:

Starting ChromeDriver 96.0.4664.45 (76e4c1bb2ab4671b8beba3444e61c0f17584b2fc-refs/branch-heads/4664@{#947}) on port 25710
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Led 06, 2022 3:49:31 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
#007bff
#007bff
Related