DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Generate and Read Barcode in Java

A barcode is a visual, machine-readable representation of data; the data usually describes something about the object that carries the barcode. Barcodes have been widely used in many fields such as commodity circulation, book management, postal management, banking system, etc.

In this blog post, I am going to introduce how to generate and read some popular 1D and 2D barcodes using Free Spire.Barcode for Java. Below is a list of barcode types supported by the free version.

Barcode Types Generate Read
CODABAR
CODE_11
CODE_39
CODE_39_EXTENDED
CODE_93
CODE_93_EXTENDED
CODE_128
EAN_8
EAN_13
EAN_128 ×
EAN_14
SCC_14
POST_NET ×
QR_CODE ×

For more barcode types, try the commercial version of Spire.Barcode.

Generate Barcode Image

There are two important classes involved in generating barcode, one is BarcodeSettings, the other is BarcodeGenerator. BarcodeSettings is used to customize your barcode with the specific type, data, size, color, etc. BarcodeGenerator is used to create image data based on the barcode settings.

//create an instance of BarcodeSetteings
BarcodeSettings settings = new BarcodeSettings();
//set barcode type
settings.setType(BarCodeType.CODE_39);
//set barcode data
settings.setData("ZXC98-HK");
//set the display text
settings.setData2D("ZXC98-HK");
//show text on bottom
settings.setShowTextOnBottom(true);
//set the border invisible
settings.hasBorder(false);
//create BarCodeGenerator object based on settings
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
//generate image data 
BufferedImage bufferedImage = barCodeGenerator.generateImage();
//write image data to a .png format file
ImageIO.write(bufferedImage, "png", new File("Code39.png"));

Output:
Format text content

Read Barcode from Image

To read the barcode image generated above, use scanOne() method of BarcodeScanner class.

String data = BarcodeScanner.scanOne("G:\\idea-projects\\spire.barcode samples\\Code39.png");
System.out.print(data);

If your image has more than one barcodes, use scan() method instead to return scan results in a string array.

String[] data = BarcodeScanner.scan(string imgPath);

Output:

Format text content

Top comments (0)