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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Generate QR Code image from Java Program"

  1. bobbell2 says:

    Hello,i want to <a href="http://www.keepautomation.com/guide/barcode_ireport.html
    "generate qr code in iReport and i need to create high quality qr code barcodes in java iReport through JARenderable implementation. This can be achieved?I would appreciate it if anyone provide me with a sample code,thanks

Leave a Reply


six × = 30



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close