DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

David has posted 86 posts at DZone. View Full User Profile

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

06.11.2014
| 415 views |
  • submit to reddit
// 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"));
     }
}
reader.close();

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.