Generate Barcode In Java Using ZXing Library

In this article we will see how to generate barcode in java. We are going to use ZXing (Zebra Crossing) library for this. Below is an example of Barcode. Open your mobile's camera and put that in front of this image (Barcode) and you will see URL as http://www.infybuzz.com which is basically data this barcode is containing.






You may have seen this kind of barcode on products like book.

So lets get started by adding ZXing dependencies. Add below dependencies in your pom.xml OR build.gradle file.


		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>core</artifactId>
			<version>3.4.1</version>
		</dependency>

		<dependency>
			<groupId>com.google.zxing</groupId>
			<artifactId>javase</artifactId>
			<version>3.4.1</version>
		</dependency>


After this lets move to code part to generate Barcode for text data that is http://www.infybuzz.com

import java.nio.file.Paths;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;

public class GenerateBarcode {

	public static void main(String[] args) {
		
		try {
			
			String text = "http://www.infybuzz.com";
			String path = "D:\\Barcode\\barcode.jpg";
			
			Code128Writer writer = new Code128Writer();
			BitMatrix matrix = writer.encode(text, BarcodeFormat.CODE_128, 500, 300);
			
			MatrixToImageWriter.writeToPath(matrix, "jpg", Paths.get(path));
			
			System.out.println("Barcode created...");
			
		} catch(Exception e) {
			System.out.println("Error while creating barcode");
		}
	}

}

0 Comments