Thursday, November 13, 2014

Java - How to generate and read QR codes

What is a QR Code?

http://en.wikipedia.org/wiki/QR_code


How can it be used?

QR code is a machine format of a text or a url or a contact. and becomes a single entity. The entity can be easily scanned by mobile phones using their cameras to get the original content.

Sample code

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
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 java.util.Vector;
import javax.imageio.ImageIO;

/**
 *
 * @author opell
 */
public class QRCodeUtility {

    public static void main(String[] args) throws WriterException, IOException, NotFoundException, ChecksumException, FormatException {
        String message = "Hello world";
        File file = new File("d:/testqr2.png");
        int width = 125;
        int height = 125;
        QRCodeUtility qrCoderead = new QRCodeUtility();
        QRCodeUtility.createQRImage(message, file, width, height);
        System.out.println(qrCoderead.readQRImage(file));
    }

    public static String readQRImage(File file) throws NotFoundException, ChecksumException, FormatException, IOException {
        LuminanceSource ls = new BufferedImageLuminanceSource(
                ImageIO.read(file));
        Result result = new QRCodeReader().decode(
                new BinaryBitmap(new HybridBinarizer(ls)));
        Vector byteSegments = (Vector) result.getResultMetadata()
                .get(ResultMetadataType.BYTE_SEGMENTS);
        int i = 0;
        int tam = 0;
        for (Object o : byteSegments) {
            byte[] bs = (byte[]) o;
            tam += bs.length;
        }
        byte[] resultBytes = new byte[tam];
        i = 0;
        for (Object o : byteSegments) {
            byte[] bs = (byte[]) o;
            for (byte b : bs) {
                resultBytes[i++] = b;
            }
        }
        String s = new String(resultBytes);
        return s;
    }

    public static BufferedImage createQRImage(String message, File file,
            int width, int height) 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(message,
                BarcodeFormat.QR_CODE, width, height, 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, "PNG", file);
        return image;
    }

}



No comments:

Post a Comment