Over a million developers have joined DZone.

How to Read & Mark Barcode Regions in an Image inside Java Applications

DZone's Guide to

How to Read & Mark Barcode Regions in an Image inside Java Applications

· ·
Free Resource

This technical tip shows how to read an image and mark the barcode regions for all recognized barcodes in the image. The barcode region is the part of the image that only contains the barcode itself. In a large image, there may be other texts or images as well as the barcode. Getting the barcode region separates the barcodes from other elements in the image by marking their edges or by filling them with a color.

To mark a barcode region:

  • Read the barcodes in the image using the BarCodeReader.read() method.
  • Get the region of the barcode using the BarCodeReader.getRegion() method, which returns an instance of the BarCodeRegion type.
  • Draw edges around the barcode using the BarCodeRegion.drawBarCodeEdges() method.
// Create an instance of BarCodeReader class and specify the image and symbology
BarCodeReader reader;
reader = new BarCodeReader("c:\\Code39Extended.png", BarCodeReadType.getCode39Extended());
int counter = 0;

// Read all the barcodes from the images
while (reader.read())
     // Display the symbology type
     System.out.println("BarCode Type: " + reader.getReadType());
     // Display the codetext
     System.out.println("BarCode CodeText: " + reader.getCodeText());
     // Get the barcode region
     com.aspose.barcoderecognition.BarCodeRegion region = reader.getRegion();
     if (region != null)
         // Initialize an object of type BufferedImage to get the Graphics object
         BufferedImage bufferedImage = ImageIO.read(new File("c:\\Code30Extended.png"));
         // Initialize graphics object from the image
         Graphics g = bufferedImage.getGraphics();
         // Initialize paint object
         Paint p = new GradientPaint(0, 0, Color.red, 100, 100, Color.pink, true);
	 // Initialize stroke object	 
         Stroke stroke = new BasicStroke(4.0f);
         region.drawBarCodeEdges((Graphics2D)g, stroke, p);
         // Save the image
         ImageIO.write(bufferedImage, "png",new File("C:\\ab\\Image001.png"));

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}