Java QR Code Generator – zxing example


SUBMITTED BY: inzi

DATE: March 31, 2017, 10:54 a.m.

FORMAT: Java

SIZE: 2.2 kB

HITS: 560

  1. Java QR Code Generator zxing example
  2. package com.journaldev.qrcode.generator;
  3. import java.awt.Color;
  4. import java.awt.Graphics2D;
  5. import java.awt.image.BufferedImage;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.Hashtable;
  9. import javax.imageio.ImageIO;
  10. import com.google.zxing.BarcodeFormat;
  11. import com.google.zxing.EncodeHintType;
  12. import com.google.zxing.WriterException;
  13. import com.google.zxing.common.BitMatrix;
  14. import com.google.zxing.qrcode.QRCodeWriter;
  15. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  16. public class GenerateQRCode {
  17. /**
  18. * @param args
  19. * @throws WriterException
  20. * @throws IOException
  21. */
  22. public static void main(String[] args) throws WriterException, IOException {
  23. String qrCodeText = "http://www.journaldev.com";
  24. String filePath = "D:\\Pankaj\\JD.png";
  25. int size = 125;
  26. String fileType = "png";
  27. File qrFile = new File(filePath);
  28. createQRImage(qrFile, qrCodeText, size, fileType);
  29. System.out.println("DONE");
  30. }
  31. private static void createQRImage(File qrFile, String qrCodeText, int size,
  32. String fileType) throws WriterException, IOException {
  33. // Create the ByteMatrix for the QR-Code that encodes the given String
  34. Hashtable hintMap = new Hashtable();
  35. hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
  36. QRCodeWriter qrCodeWriter = new QRCodeWriter();
  37. BitMatrix byteMatrix = qrCodeWriter.encode(qrCodeText,
  38. BarcodeFormat.QR_CODE, size, size, hintMap);
  39. // Make the BufferedImage that are to hold the QRCode
  40. int matrixWidth = byteMatrix.getWidth();
  41. BufferedImage image = new BufferedImage(matrixWidth, matrixWidth,
  42. BufferedImage.TYPE_INT_RGB);
  43. image.createGraphics();
  44. Graphics2D graphics = (Graphics2D) image.getGraphics();
  45. graphics.setColor(Color.WHITE);
  46. graphics.fillRect(0, 0, matrixWidth, matrixWidth);
  47. // Paint and save the image using the ByteMatrix
  48. graphics.setColor(Color.BLACK);
  49. for (int i = 0; i < matrixWidth; i++) {
  50. for (int j = 0; j < matrixWidth; j++) {
  51. if (byteMatrix.get(i, j)) {
  52. graphics.fillRect(i, j, 1, 1);
  53. }
  54. }
  55. }
  56. ImageIO.write(image, fileType, qrFile);
  57. }
  58. }

comments powered by Disqus