Java Barcode API

QR Code "9780201750799"

QR Code for "9780201750799"

Overview

Originally Barcodes were 1D representation of data using width and spacing of bars. Common bar code types are UPC barcodes which are seen on product packages. There are 2D barcodes as well (they are still called Barcodes even though they don’t use bars). A common example of 2D bar code is QR code (shown on right) which is commonly used by mobile phone apps. You can read history and more info about Barcodes on Wikipedia.

There is an open source Java library called ‘zxing’ (Zebra Crossing) which can read and write many differently types of bar codes formats. I tested zxing and it was able to read a barcode embedded in the middle of a 100 dpi grayscale busy text document!

This article demonstrates how to use zxing to read and write bar codes from a Java program.

Getting the library

It would be nice if the jars where hosted in a maven repo somewhere, but there is no plan to do that (see Issue 88). Since I could not find the binaries available for download, I decided to download the source code and build the binaries, which was actually quite easy.

The source code of the library is available on Google Code. At the time of writing, 1.6 is the latest version of zxing.

1. Download the release file ZXing-1.6.zip (which contains of mostly source files) from here.
2. Unzip the file in a local directory
3. You will need to build 2 jar files from the downloaded source: core.jar, javase.jar

Building core.jar

cd zxing-1.6/core
mvn install

This will install the jar in your local maven repo. Though not required, you can also deploy it to your company’s private repo by using mvn:deploy or by manually uploading it to your maven repository.

There is an ant script to build the jar as well.

Building javase.jar

Repeat the same procedure to get javase.jar

cd zxing-1.6/javase
mvn install

Including the libraries in your project

If you are using ant, add the core.jar and javase.jar to your project’s classpath.

If you are using maven, add the following to your pom.xml.

<dependencies>
 <dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>1.6-SNAPSHOT</version>
 </dependency>
 
 <dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>1.6-SNAPSHOT</version>
 </dependency>
<dependencies>

Once you have the jars included in your project’s classpath, you are now ready to read and write barcodes from java!

Reading a Bar Code from Java

You can read the bar code by first loading the image as an input stream and then calling this utility method.

InputStream barCodeInputStream = new FileInputStream("file.jpg");
BufferedImage barCodeBufferedImage = ImageIO.read(barCodeInputStream);

LuminanceSource source = new BufferedImageLuminanceSource(barCodeBufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Reader reader = new MultiFormatReader();
Result result = reader.decode(bitmap);

System.out.println("Barcode text is " + result.getText());

Writing a Bar Code from Java

You can encode a small text string as follows:

String text = "98376373783"; // this is the text that we want to encode

int width = 400;
int height = 300; // change the height and width as per your requirement

// (ImageIO.getWriterFormatNames() returns a list of supported formats)
String imageFormat = "png"; // could be "gif", "tiff", "jpeg" 

BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File("qrcode_97802017507991.png")));

In the above example, the bar code for “97802017507991″ is written to the file “qrcode_97802017507991.png” (click to see the output).

JavaDocs and Documentation

The Javadocs are part of the downloaded zip file. You can find a list of supported bar code formats in the Javadocs. Open the following file to see the javadocs.

zxing-1.6/docs/javadoc/index.html

Reference

Related posts:

  1. 2 ways to convert Java Map to String
  2. How to copy bean properties with a single line of code
  3. Calling a static method from EL
  4. Maven Selenium

49 comments to Java Barcode API

  • Richard

    hello,

    I am currently working on software for student attendance. I use the flex / flash and php to create the software but I faced a problem barcode scanner (Motorola-type barcode scanner Symbol LS2208 Laser Barcode Scanner – USB), can not connect to the application to call the data from the database when students scan the barcode printed on their student card.

    Can you help me to make the script so that it can run on flex / flash and php. it makes me crazy for a week to seek a way out …. please help me (I have not mastered the java script)

    thanks,

    ps : i use flex / flash cs 5

    table is: name, grade, address, barcode number, clock in, clock out. after all data is stored in the database, it’s time to call one by one using a barcode scanner. but only wrote the inputted barcode number on the barcode column that appears and do not call the data from the database in accordance with the code barcode from the student card.

  • Rupesh Saxena

    Hello,
    Is your API capable of reading MICR codes which are found on the bank checks. If not then can you tell me from where I can download the MICR Reader API.

    thanks & regards,

    Rupesh Saxena

  • vineet

    zxing supports the following barcode formats:

    AZTEC: Aztec 2D barcode format.
    CODABAR: CODABAR 1D format.
    CODE_128: Code 128 1D format.
    CODE_39: Code 39 1D format.
    CODE_93: Code 93 1D format.
    DATA_MATRIX: Data Matrix 2D barcode format.
    EAN_13: EAN-13 1D format.
    EAN_8: EAN-8 1D format.
    ITF: ITF (Interleaved Two of Five) 1D format.
    PDF417: PDF417 format.
    QR_CODE: QR Code 2D barcode format.
    RSS_EXPANDED: RSS EXPANDED
    RSS14: RSS 14
    UPC_A: UPC-A 1D format.
    UPC_E: UPC-E 1D format.
    UPC_EAN_EXTENSION: UPC/EAN extension format.

    Reference:
    http://zxing.org/w/docs/javadoc/com/google/zxing/BarcodeFormat.html

    For a format not supported by this library you’ll need to find another library. I’m not familiar with MICR, but google search of +micr barcode java does yield some promising results.

  • El Pauer

    Aztec barcode isn’t currently supported by Zxing 1.6.

  • sam

    Vineet,
    Thanks for the lovely article I need to have a Barcode / Label generate , I am creating few data entry forms and on saving those forms all I want to have is the barcode to be generated which would be unique number and save that in the database I am using mySQL.. since you have the harcoded string can we have something which is going to be automatically created and then saved in the DB

  • adrian

    hello,
    i’m working with blackberry application..and i want to use QR barcode as a trigger to input database..is this possible ? and could you give reference on how the QR barcode could do this logic.. ? thx

  • Developperand

    hello,
    i’m facing problem, I tried to make the code of this tutorial to work, but it seems there is problem related to the laibrary awt, because i’m not able to resolve the BufferefImage class
    can any one please help me , if you had yet work with this example, thks

  • vineet

    Which JVM are you using?

    java -version

    BufferedImage is part of the JVM, so you should have it.

    Make sure you have the following import declaration:
    import java.awt.image.BufferedImage;

  • Developperand

    thanks for your answer
    here the version of JVM
    java version “1.6.0_17″
    Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
    Java HotSpot(TM) Client VM (build 14.3-b01, mixed mode, sharing)

  • vineet

    Does the import not work for you, do you get a compiler error?

  • Developperand

    actually, I’m testing this example into android project, so it can be the cause that the android doesn’t support this library

  • nikko

    hello,
    i tried your code to generate a barcode and i got this error “cannot find symbol class QRCodeWriter”. could you tell me how to fix this?
    thanks

  • nikko

    hello again,
    it turns out i need to include “import com.google.zxing.qrcode.QRCodeWriter;”

  • Hi Vineet,
    do you have a example how I can use the UPC_EAN_EXTENSION?

  • Sony

    Hi Vineet,thanks for share your code, usefull & simple.
    It’s very helpfull for me.

    Thanks again.
    Sony
    Argentina.

  • jitendra

    Hi

    i done coding for reading QR Code as per ur Guidelines but i get com.google.zxing.NotFoundException

  • Keith

    Great example, thanks! I got your example running and got a PNG good looking QR code.

    I see in the comments I can get “gif”, “tiff”, or “jpeg”. I changed the imageFormat variable to jpeg. It created a good looking QR barcode, except the colors are off. The “white” is a peach color, and the “black” is a blue/green color. Any idea what I’m doing wrong?

    Here is the QR barcode: http://imgur.com/QnNXO

  • Keith

    I have stumbled upon the answer to my question above. Inside the ZXing class MatrixToImageWriter a BufferedImage object is created with BufferedImage.TYPE_INT_ARGB as the 3rd argument. By changing this to BufferedImage.TYPE_INT_RGB the colors for jpeg are turning out black and white as expected.

  • vineet

    Hi Keith, thanks for sharing the answer!

  • Alex

    This qrcode corresponds to the standard ISO/IEC 18004:2000???????

  • Gnana Prakash

    Hi Vineet,

    Thanks for sharing this information.Am able to get barcode at different format like QR_CODE,EAN_13,EAN_8 etc. But I need to get numbers below the barcode,I tried it but unable to get that one..only barcode image is displayed and do you have any idea reg this.

    Thanks in advance

  • Rafeek

    Hello vineeth,
    i hope you are ready to help me, i wish to write a pgm in struts2 using a barcode program , pls send code for that

  • Ashu

    Hi,
    i need to convert an integer to a barcode and have to return the barcode as an bytearray

  • omar

    hi i want to read the QR code direcly from a webcam using JMF can you help me :)

  • Ahmed

    Hi Vineet,
    nice post, the instructions were very detailed and nice example. I used eclipse for my jar files, incase someone out there needs help with that.

    i was wondering if you had an example on using a regular 1D classic barcode. (think its UPCEA…) , i cant seem to get that to work after going over the javadoc several times.

    i want to use something else other than QR code writer.

    thanls

  • Ahmed

    @Gnana,

    any help, how did u implement the other bard code types, any example code

  • Nour

    Hello Vineet,

    thank you for the the well explained article, it was really very helpful to me.
    in fact i was able to generate barcodes in different format using java and read them with (Honeywell Voyager MS9520) hand held scanner.
    i had success with the following formats: ITF, CODE39, CODE 128. but the scanner didn’t detect any text from the barcode printed label on EAN8 and EAN13 formats. I in fact tried to read the barcode images using Zxing reader utility but nothing happens apart from an exception thrown saying [java.lang.ArrayIndexOutOfBoundsException: -5] for EAN8 and [java.lang.ArrayIndexOutOfBoundsException: -6] for EAN13. i have to add that the image format i used is GIF and till now i don’t know what would be the problem.

    Nour

  • vineet

    Hi Nour,

    Sorry but I don’t know the answer to that. You might want to post your question to the Zing mailing list (http://groups.google.com/group/zxing?pli=1).

    Vineet

  • lakshmi narayan

    does it support Rs232 scanner ?if not how

  • Nour

    Hi Vineet, Hi Lakshmi narayanm

    thanks for your replies.
    yes Lakshmi the scanner supports Rs232.

    Well, i managed after a better reading of EAN8 and EAN13 specifications to solve the problem.
    Finally i realized the problem was with the CheckSum, as EAN8 and EAN13 both use Modulo 10 calculation to do the checksum.
    Zxing unfortunately creates a barcode with wrong checksum and doesn’t throw any exception in case of writing a barcode, and then it throws a stange exception in case of reading a barcode with a wrong checksum.
    for that reason i decided to collect/improvise a barcode value less one digit (7 for EAN8, 12 for EAN13) then do the Modulo 10 calculation to finally append the checksum result as the last digit required for the text length.
    i was able to generate and read a barcode with BOOKLAND and UPC-A formats as well, as they are a subset of EAN13.

    EAN8 maximum text length is 8, EAN13 maximum text length is 13 + a possible extension of +2 or +5 digits for both.
    I dont think Zxing supports +2 or +5 digits extension for EAN8/EAN13. i didn’t try it yet, but i will very soon.

    http://barcode4j.sourceforge.net/2.1/symbol-ean-8.html#structure
    http://www.makebarcode.com/specs/ean_13.html
    http://www.makebarcode.com/specs/bookland.html

    here the class Writer of the barcode + checksum utility i added. All and before all thanks to Vineet that i arrived to this stage where i am implementing these utilities in a Swing application.

    Nour E Ghtami
    Casablanca – Morocco

    class WriteBarCode{
    public String ErLog = "shopresourses/error/";
    BitMatrix bitMatrix = null;
    public String Form = "", text = "", PicName = "";
    public String imageFormat = "png";
    public int width = 0; int height = 36;
    public WriteBarCode(){}
    public WriteBarCode(String Form, String Str, String PicName)
    {
    this.Form = Form; this.text = Str; this.PicName = PicName;
    }
    int Innwidth = 0;
    public void WriteNewBarCode()
    {
    // start writing barcode
    String ErrStr = "";
    if(Form.equals("EAN8")){ text += "" + Ean8CheckSum(text); try{ bitMatrix = new EAN8Writer().encode(text, BarcodeFormat.EAN_8, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("EAN13")){ text += "" + Ean13CheckSum(text); try{ bitMatrix = new EAN13Writer().encode(text, BarcodeFormat.EAN_13, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("UPC-A")){ text = "0" + text; text += Ean13CheckSum(text); try{ bitMatrix = new EAN13Writer().encode(text, BarcodeFormat.EAN_13, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("BOOKLAND")){ text = "978" + "0" + text; text += Ean13CheckSum(text); try{ bitMatrix = new EAN13Writer().encode(text, BarcodeFormat.EAN_13, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("CODE39")){ try{ bitMatrix = new Code39Writer().encode(text, BarcodeFormat.CODE_39, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("CODE128")){ try{ bitMatrix = new Code128Writer().encode(text, BarcodeFormat.CODE_128, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("ITF")){ try{ bitMatrix = new ITFWriter().encode(text, BarcodeFormat.ITF, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }
    else if(Form.equals("QR_CODE")){ try{ bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height); }catch(com.google.zxing.WriterException we){ new LogWriter("" + we + "\n", ErLog); } }

    File file = new File(PicName);
    FileOutputStream fop = null;
    try
    {
    fop = new FileOutputStream(file);
    MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, fop);
    }
    catch(Exception e){ new LogWriter("" + e + "\n", ErLog); }
    // end writing barcode

    // adding white rectagle on the bottom part of the barcode with its value
    try
    {
    File Orig_File = new File(PicName);
    BufferedImage bimg = ImageIO.read(Orig_File);
    Innwidth = bimg.getWidth(); int height = bimg.getHeight();
    if(!Form.equals("QR_CODE"))
    {
    // drawing white rectangle on bufferedimage
    int rgb = 0xffffff;
    for(int i = height-12; i < height; i++){ for(int j = 0; j < Innwidth; j++){ bimg.setRGB(j, i, rgb); } }

    java.awt.Font NuF = new java.awt.Font("courier",java.awt.Font.PLAIN, 12);
    FontRenderContext frc = bimg.getGraphics().getFontMetrics().getFontRenderContext();
    Rectangle2D rect = NuF.getStringBounds(text,frc);
    int StrW = (int)rect.getWidth();
    int LeftXPos = (Innwidth-StrW)/2;

    Graphics g = bimg.createGraphics();
    g.setColor(Color.black);
    g.setFont(NuF); g.drawString(text,LeftXPos,height);
    ImageIO.write(bimg, imageFormat, new File(PicName));
    g.dispose();
    }
    }catch(Exception e){ new LogWriter("" + e + "\n", ErLog); }
    try{ fop.flush(); fop.close(); }catch(IOException ioe){ new LogWriter("" + ioe + "\n", ErLog); }
    }

    // checksum utility
    public int Ean13CheckSum(String Str)
    {
    int DigitValue = 0; int CodeLen = Str.length();
    int CodeValue[] = new int[CodeLen];
    if(CodeLen < 13)
    {
    for(int c = 0; c < CodeLen; c ++){ CodeValue[c] = Integer.parseInt(Str.substring(c,c+1)); }
    int Odd = (CodeValue[0] + CodeValue[2] + CodeValue[4] + CodeValue[6] + CodeValue[8] + CodeValue[10]) * 3;
    int Even = CodeValue[1] + CodeValue[3] + CodeValue[5] + CodeValue[7] + CodeValue[9] + CodeValue[11];
    int Sum = Odd + Even;
    DigitValue = 10 - (Sum % 10);
    DigitValue = (DigitValue == 10) ? 0 : DigitValue;
    } return DigitValue;
    }

    public int Ean8CheckSum(String Str)
    {
    int DigitValue = 0; int CodeLen = Str.length();
    int CodeValue[] = new int[CodeLen];
    if(CodeLen < 8)
    {
    for(int c = 0; c < CodeLen; c ++){ CodeValue[c] = Integer.parseInt(Str.substring(c,c+1)); }
    int Odd = (CodeValue[0] + CodeValue[2] + CodeValue[4] + CodeValue[6]) * 3;
    int Even = CodeValue[1] + CodeValue[3] + CodeValue[5];
    DigitValue = ( 10 - ((Odd + Even) % 10) ) % 10;
    DigitValue = (DigitValue == 10) ? 0 : DigitValue ;
    } return DigitValue;
    }
    }

    (BOOKLAND and UPC-A formats are not fully tested)

  • Nour

    Hi,

    this is a small correction for Ean13CheckSum method.
    i did reverse the order of the odd/even digits in the previous posting. here is a good one after tests. it’s working fine for EAN13, UPC-A and BOOKLAND.

    int Even = CodeValue[0] + CodeValue[2] + CodeValue[4] + CodeValue[6] + CodeValue[8] + CodeValue[10];
    int Odd = (CodeValue[1] + CodeValue[3] + CodeValue[5] + CodeValue[7] + CodeValue[9] + CodeValue[11]) * 3;

    note for BOOKLAND format that the value 978 + 0 or 1, a total of 4 digits has to be prefixed to the 8 digits(maximum text length before prefixation), then the checksum value affixed to the whole text giving a length of 13 digits before any attempt to generate a valid scannable barcode.

    Thanks

  • How to generate jar files core.jar and javase.jar

  • kk

    hi all,
    I’m able to use the code given here for both generating as well as decoding QR code and its working fine in my windows 7 sytem through Eclipse. But, when I tried to use the same code in Android , its giving me errors, as AWT is not supported in Android. I’m getting the same errors as reported by @Developperand
    Can someone help me how to fix this error or what is the alternative way to generate QR code in Android. Many thanks for your time.

  • kk

    @Kanwal Nain Singh
    You can use the following instructions to generate the JAR files.
    For core jar file:
    1. cd zxing-1.6/core
    2. ant

    and similarly for j2se jar
    2. cd zxing-1.6/javase
    2. ant

    hope that helps. thanks.

  • vineet

    Hi Kanwal, thanks for sharing the solution!

  • Gemma

    Hi,
    In the type CODE 128 BarcodeFormat which codes subset A,B or C is implemented ? I didn’t find in javadocs an input parameter to choose the subset, i.e. in Code128Writer,
    have you any suggestion? Many Thanks

  • Vineet,

    We are looking to buy Barcode API for our software – but it is very costly – is there any way that you can help and give us full API code – we are ready to pay for that – we are looking for open source Barcide API which is suppport all linear Barcode

    email id :- info@singhtransport.biz

    Tim

  • venkat

    i have written barcode code in java use io package, by using that generate samplebarcode.txt file in some folder, after that directly send to the barcode printer then it is printed as it is code but i could not print the barcode through barcode printer,now i want to print the barcode what i have to do?please needful for me…..

  • chandu

    hi Vineet
    i had used ur code i.e.

    BitMatrix bitMatrix = new QRCodeWriter().encode(text, BarcodeFormat.QR_CODE, width, height);

    while compilation it shows an error of incompatible types.
    please give me solution :)
    thank you

  • Syed Jawahar

    Vineet,

    Thanks for the article, very useful.

    Regards
    Jawahar

  • irgendeiner

    Hi Vineet,

    thank you for sharing this minimum example. It helped me a lot.

    thank you, regards

  • mark

    Hi
    can anyone please tell me how to give human readable text below the bar code generated using zxing.
    Thanks in advance. i am using code 128

    code is as below-

    —————————-
    String text = “12345678″; // this is the text that we want to encode

    int width = 400;
    int height = 300; // change the height and width as per your requirement

    // (ImageIO.getWriterFormatNames() returns a list of supported formats)
    String imageFormat = “png”; // could be “gif”, “tiff”, “jpeg”

    BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.CODE_128, width, height);
    MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, new FileOutputStream(new File(“barcode.png”)));
    ————————————————

  • Hi I tried building my standalone barcode scanner using above method but i am not able to build even the jar files.

  • Richa

    Hi Vinit,

    I went through the blog. can you please tell me why we are generating two jar files from the same code?
    I guess this will lead to heavy file size(apk file).

  • swapnil

    hii @Vineet @nour

    Thankss for the tutorial.. but still i have some doubt
    actually in my case i already have a barcode so there is no need to generate the barcode..
    but for reading purpose i m using i-ball cs153 laser barcode scanner in your code it take a image file as input and then doing encoding process.
    what changes i have to do in ur code so that whenever scanner read barcode then our code read it

    any type of help is highly appreciated
    Thanksss

  • Tim Dong

    I need to read barcodes from an Usb barcode reader into a textbox using Java. I am now to API. I am using a Mecer Usb barcode reader

  • Fra

    Hi Vineet (and thanks a lot) and hi everyone.
    Somebody know how to do what Gnana Prakash wanted to do?

    Gnana Prakash
    May 21st, 2011 at 11:44 pm
    Hi Vineet,
    Thanks for sharing this information.Am able to get barcode at different format like QR_CODE,EAN_13,EAN_8 etc. But I need to get numbers below the barcode,I tried it but unable to get that one..only barcode image is displayed and do you have any idea reg this.

    Thanks in advance.

  • Swapnil

    Thanks for taking time to post it man!
    This thing is going to be my weekend project :)

  • mark

    Hello vineet,

    I am a android developer i want to generate barcodes in my app with some data. how can i use these libraries in my project and how to develop the code.

    please give replay thanks in advance,

    Regards
    Mark

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Get Adobe Flash playerPlugin by wpburn.com wordpress themes