skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Thursday, October 4, 2012

Bar Code Generation From Java

Posted by Admin at 12:36 PM – 0 comments
 
To generate BarCode in image format from JAVA, i propose this solution. The generated BarCode image can be scanned and it will produce the codeValue as output.

To achieve this, we should use barbecue-1.1.jar which provides BarCode related APIs. This jar should be added to the classpath.

The CodeValue and imageName should be passed as argument to the drawingBarcodeForCodeValue() method

codeValue - The value for which BarCode image should be generated
imageName - The name of the barCode image. Complete path should be given here. Ex: C:/sampleBarCode.jpeg.

In the below code snippet we have used Code128 encoding. This value can be customized according to the project requirement. similar to createCode128() method, many other encoding methods are present in BarcodeFactory class. BarCode height, width can be customized to project requirements
public static void drawingBarcodeForCodeValue(String codeValue, String imageName) throws BarcodeException, OutputException
{
 // Always get a Barcode from the BarcodeFactory
 Barcode barcode = BarcodeFactory.createCode128(codeValue);
 barcode.setDrawingText(false);
 barcode.setBarHeight(50);
 barcode.setBarWidth(50);

 BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_BYTE_GRAY);
 // We need to cast the Graphics from the Image to a Graphics2D
 Graphics2D g = (Graphics2D) image.getGraphics();
 // Barcode supports a direct draw method to Graphics2D that lets you position the
 // barcode on the canvas
 barcode.draw(g, 10, 56);

 try
 {
                         // The imageName should be the complete path where the image should be stored. The image should be a jpeg file.
                         // Give the image name with .jpeg extension. Ex: C:/sampleImage.jpeg 
     File f = new File(imageName);
     FileOutputStream fileOutputStream = new FileOutputStream(f);
     // Let the barcode image handler do the hard work
     BarcodeImageHandler.outputBarcodeAsJPEGImage(barcode, fileOutputStream);
 }
 catch (Exception exception)
 {
     System.out.println("Exception occured while drawing barCode:" + exception.toString());
     exception.printStackTrace();   
 }
}


Leave a Reply

Newer Post Older Post
Subscribe to: Post Comments ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger