How to automate BarCode using ZXing API in Selenium

In this article I will explain how to automate Bar code in Selenium Webdriver.

What is Bar Code?
Bar Code is a machine-readable optical label that contains information about the item to which it is attached.

A Bar code is the small image of lines (bars) and spaces that is affixed to retail store items, identification cards, and postal mail to identify a particular product number, person, or location.

Selenium has limitation to automate Bar code but by using third party API we can automate Bar codes.

So, ZXing is one the third party API will be used to automate Bar Codes.


We need to download Zxing API from below links:


You can also generate your own Bar Codes using below link:

Now, I'm going to automate Bar code which is available on below application. https://testautomationpractice.blogspot.com/

Code Snippet:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class ReadingBarCode {
public static void main(String[] args) throws IOException, NotFoundException {
System.setProperty("webdriver.chrome.driver", "C:/Drivers/chromedriver_win32/chromedriver.exe");
WebDriver driver=new ChromeDriver();
String barCodeURL=driver.findElement(By.xpath("//*[@id=\"HTML12\"]/div[1]/img")).getAttribute("src");
//String barCodeURL=driver.findElement(By.xpath("//*[@id=\"HTML12\"]/div[1]/img[2]")).getAttribute("src");

URL url=new URL(barCodeURL);
BufferedImage bufferedimage=ImageIO.read(url);
LuminanceSource luminanceSource=new BufferedImageLuminanceSource(bufferedimage);
BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(luminanceSource));
Result result =new MultiFormatReader().decode(binaryBitmap);


Post a Comment