Generate QR Code image from Java Program

If you are tech and gadget savvy, then you must be aware of QR codes. You will find it everywhere these days – in blogs, websites and even in some public places. This is very popular in mobile apps, where you scan the QR code using a QR Code scanner app and it will show you the text or redirect you to the web page if it’s URL. I came across this recently and found it very interesting. If you want to know about QR Code, you can find a lot of useful information at Wikipedia QR Code Page.When I found these kind of images in so many websites then I started looking how to generate it using Java Code. I looked into some APIs available as open source in the market and found zxing to be the simplest and best to use.

Here is the program you can use to create QR Code image with zxing API.

package com.adly.generator;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

public class GenerateQRCode {

 /**
  * @param args
  * @throws WriterException
  * @throws IOException
  */
 public static void main(String[] args) throws WriterException, IOException {
  String qrCodeText = 'http://www.journaldev.com';
  String filePath = 'D:\\Pankaj\\JD.png';
  int size = 125;
  String fileType = 'png';
  File qrFile = new File(filePath);
  createQRImage(qrFile, qrCodeText, size, fileType);
  System.out.println('DONE');
 }

 private static void createQRImage(File qrFile, String qrCodeText, int size,
   String fileType) throws WriterException, IOException {
  // Create the ByteMatrix for the QR-Code that encodes the given String
  Hashtable hintMap = new Hashtable();
  hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
  QRCodeWriter qrCodeWriter = new QRCodeWriter();
  BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText,
    BarcodeFormat.QR_CODE, size, size, hintMap);
  // Make the BufferedImage that are to hold the QRCode
  int matrixWidth = byteMatrix.getWidth();
  BufferedImage image = new BufferedImage(matrixWidth, matrixWidth,
    BufferedImage.TYPE_INT_RGB);
  image.createGraphics();

  Graphics2D graphics = (Graphics2D) image.getGraphics();
  graphics.setColor(Color.WHITE);
  graphics.fillRect(0, 0, matrixWidth, matrixWidth);
  // Paint and save the image using the ByteMatrix
  graphics.setColor(Color.BLACK);

  for (int i = 0; i < matrixWidth; i++) {
   for (int j = 0; j < matrixWidth; j++) {
    if (byteMatrix.get(i, j)) {
     graphics.fillRect(i, j, 1, 1);
    }
   }
  }
  ImageIO.write(image, fileType, qrFile);
 }

}

Here is the QR Code image file created by this program. You can use your mobile QR Code scanner app to test it. It should point to JournalDev Home URL.

If you don’t have a mobile app to test it, don’t worry. You can test it with zxing API through command line too.

I am on Windows OS and here is the command to test it. If you are on Unix/Linux/Mac OS then change it accordingly.

D:\Pankaj\zxing>java -cp javase\javase.jar;core\core.jar com.google.zxing.client.j2se.CommandLineRunner D:\Pankaj\JD.png
file:/D:/Pankaj/JD.png (format: QR_CODE, type: URI):
Raw result:

http://www.journaldev.com

Parsed result:

http://www.journaldev.com

Found 4 result points.
  Point 0: (35.5,89.5)
  Point 1: (35.5,35.5)
  Point 2: (89.5,35.5)
  Point 3: (80.5,80.5)


Tip for Dynamic QR Code Generation

If you want to generate QR code dynamically, you can do it using Google Charts Tools.
For above scenario, URL will be https://chart.googleapis.com/chartchs=125×125&cht=qr&chl=http://www.journaldev.com

Happy coding and don’t forget to share!

Reference: Generate QR Code image from Java Program from our JCG partner Pankaj Kumar at the Developer Recipes blog.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply


+ 8 = fourteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books