DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

๐ŸŒš Friends don't let friends browse without dark mode.

Just kidding, it's a personal preference. But you can change your theme, font, etc. in your settings.

The more you know. ๐ŸŒˆ