How to convert color RGB to HEX and HEX to RGB in Selenium Webdriver using Java.

We read font color by getCssValue("color") and it is RGB Format. In Software Requirement Specification (SRS) Color code is Hex format. We need to convert RGB to HEX format or HEX to RGB format for automation. I am going to describe how to convert RGB to HEX color and HEX to RGB color.


 import java.awt.Color;  
 import java.util.concurrent.TimeUnit;  
 import org.openqa.selenium.By;  
 import org.openqa.selenium.NoSuchElementException;  
 import org.openqa.selenium.WebDriver;  
 import org.openqa.selenium.firefox.FirefoxDriver;  
 public class Convertrgbtohex {  
 public static void main(String[] a) {  
 try {  
 // Initialize Firefox driver  
 WebDriver driver = new FirefoxDriver();  
 //Maximize browser window   
 driver.manage().window().maximize();  
 //Go to URL  
 driver.get("http://www.yahoo.com/");  
 //Set selenium webdriver get timeout  
 driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  
 String font_name, font_size, font_color;  
 // Get font family name  
 font_name = driver.findElement(By.partialLinkText("My Yahoo")).getCssValue("font-family").trim();  
 // Get font size  
 font_size = driver.findElement(By.partialLinkText("My Yahoo")).getCssValue("font-size").trim();  
 // Get font color RGB code  
 font_color = driver.findElement(By.partialLinkText("My Yahoo")).getCssValue("color").trim();  

 //Print font-family, font-size and font-color  
 System.out.println("font-family : " + font_name);  
 System.out.println("font-size : " + font_size);  
 System.out.println("font-color : " + font_color);  

 // Convert rgb to hex   
 String color1[];  
 color1 = font_color.replace("rgba(", "").split(",");       
 String hex = String.format("#%02x%02x%02x", Integer.parseInt(color1[0].trim()), Integer.parseInt(color1[1].trim()), Integer.parseInt(color1[2].trim()));  
 System.out.println("Convert rgb to hex : " + hex.toUpperCase());  

 //Convert hex to rgb and Print rgb code  
 System.out.println("Convert hex to rgb : rgb (" + Color.decode(hex).getRed() + ", " + Color.decode(hex).getGreen() + ", " + Color.decode(hex).getRed() + ")");  

 // Browser close   
 driver.close();  

 } catch (NoSuchElementException e) {  
 e.printStackTrace();  
     }  
   }  
 }  

No comments:

Post a Comment