Tuesday, November 22, 2011

Generate QRCode using Java

This is a little sample code to generate code using Java

You will need this class first

import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import com.google.zxing.LuminanceSource;

public final class BufferedImageLuminanceSource extends LuminanceSource {

      private final BufferedImage image;
      private final int left;
      private final int top;
      private int[] rgbData;

      public BufferedImageLuminanceSource(BufferedImage image) {
        this(image, 0, 0, image.getWidth(), image.getHeight());
      }

      public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width,
          int height) {
        super(width, height);

        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();
        if (left + width > sourceWidth || top + height > sourceHeight) {
          throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
        }

        this.image = image;
        this.left = left;
        this.top = top;
      }

      // These methods use an integer calculation for luminance derived from:
      // <code>Y = 0.299R + 0.587G + 0.114B</code>
     
      public byte[] getRow(int y, byte[] row) {
        if (y < 0 || y >= getHeight()) {
          throw new IllegalArgumentException("Requested row is outside the image: " + y);
        }
        int width = getWidth();
        if (row == null || row.length < width) {
          row = new byte[width];
        }

        if (rgbData == null || rgbData.length < width) {
          rgbData = new int[width];
        }
        image.getRGB(left, top + y, width, 1, rgbData, 0, width);
        for (int x = 0; x < width; x++) {
          int pixel = rgbData[x];
          int luminance = (306 * ((pixel >> 16) & 0xFF) +
              601 * ((pixel >> 8) & 0xFF) +
              117 * (pixel & 0xFF)) >> 10;
          row[x] = (byte) luminance;
        }
        return row;
      }

     
      public byte[] getMatrix() {
        int width = getWidth();
        int height = getHeight();
        int area = width * height;
        byte[] matrix = new byte[area];

        int[] rgb = new int[area];
        image.getRGB(left, top, width, height, rgb, 0, width);
        for (int y = 0; y < height; y++) {
          int offset = y * width;
          for (int x = 0; x < width; x++) {
            int pixel = rgb[offset + x];
            int luminance = (306 * ((pixel >> 16) & 0xFF) +
                601 * ((pixel >> 8) & 0xFF) +
                117 * (pixel & 0xFF)) >> 10;
            matrix[offset + x] = (byte) luminance;
          }
        }
        return matrix;
      }

     
      public boolean isCropSupported() {
        return true;
      }

     
      public LuminanceSource crop(int left, int top, int width, int height) {
        return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
      }

      // Can't run AffineTransforms on images of unknown format.
     
      public boolean isRotateSupported() {
        return image.getType() != BufferedImage.TYPE_CUSTOM;
      }

     
      public LuminanceSource rotateCounterClockwise() {
        if (!isRotateSupported()) {
          throw new IllegalStateException("Rotate not supported");
        }
        int sourceWidth = image.getWidth();
        int sourceHeight = image.getHeight();

        // Rotate 90 degrees counterclockwise.
        AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);

        // Note width/height are flipped since we are rotating 90 degrees.
        BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, image.getType());

        // Draw the original image into rotated, via transformation
        Graphics2D g = rotatedImage.createGraphics();
        g.drawImage(image, transform, null);
        g.dispose();

        // Maintain the cropped region, but rotate it too.
        int width = getWidth();
        return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width),
            getHeight(), width);
      }

    }

Now it's the main class

public class UsingZxingToWrite {
    // Change with other file directory
    private static final String FILENAME = "E:\\test.jpg";
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    /**
     * Renders a {@link BitMatrix} as an image, where "false" bits are rendered
     * as white, and "true" bits are rendered as black.
     */
    public static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }

    // In case the golden images are not monochromatic, convert the RGB values
    // to greyscale.
    private static BitMatrix createMatrixFromImage(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        int[] pixels = new int[width * height];
        image.getRGB(0, 0, width, height, pixels, 0, width);

        BitMatrix matrix = new BitMatrix(width, height);
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int pixel = pixels[y * width + x];
                int luminance = (306 * ((pixel >> 16) & 0xFF) + 601
                        * ((pixel >> 8) & 0xFF) + 117 * (pixel & 0xFF)) >> 10;
                if (luminance <= 0x7F) {
                    matrix.set(x, y);
                }
            }
        }
        return matrix;
    }

    public static void main(String[] args) {

        int w = 300;
        int h = 300;

        // get a byte matrix for the data
        BitMatrix bitMatrix;
        com.google.zxing.Writer writer = new MultiFormatWriter();
        try {
           
            bitMatrix = writer.encode(
                    "AIRWAYID892045",
                    //new String(contents, Charset.forName("ISO-8859-1")),
                    BarcodeFormat.QR_CODE, w, h);
        } catch (com.google.zxing.WriterException e) {
            // exit the method
            return;
        }

        File f = new File(FILENAME);
        BufferedImage image = toBufferedImage(bitMatrix);
        try {
            System.out.println("Generating... " + f.getAbsolutePath());

            ImageIO.write(image, "jpg", f);
            System.out.println("Done");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        MultiFormatReader reader = new MultiFormatReader();

        BufferedImage capturedImage;
        try {
            capturedImage = ImageIO.read(new File(FILENAME));
           
            // creating luminance source
            LuminanceSource source = new BufferedImageLuminanceSource(capturedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new  HybridBinarizer(source));

            Hashtable hints = new Hashtable(1);
            Vector formats = new Vector(1);

            formats.addElement(BarcodeFormat.QR_CODE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS,formats);
           
            Result result;
            try {
                result = reader.decode(bitmap);
                System.out.println(result.getText());
            } catch (NotFoundException e) {
                e.printStackTrace();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}

Here's the sample output


6 comments:

Gatesben said...

nice shares...get the point.....
JAVA Training In Chandigarh

Unknown said...

Thanks for sharing this informative post.

Taxi in Philadelphia

Unknown said...

I was looking this kind of post from long.. Thanks for sharing..God bless!!

web design uae

Unknown said...

Thanks for Sharing this informative post. Stay Blessed.
Bomb detection equipment

Unknown said...

This is what I was looking for from last week. Great work done. :)


Java training in chandigarh

Unknown said...

I want to use Java to generate barcode with QR Code form for retailing commodities. And my requirement is the QR Code should encode information like region and store in which the commodity is sold, department, name of the item, etc. Cam someone give some good suggestion of some framework to do that? I prefer to the none-license one.
Labels:qrcode barcode java