APP QR Code with JAVA (SWING)

Joe

Thành viên VIP
21/1/13
2,969
1,311
113
Hi
As you know, QR Code is the invention of the Japanese Company Denso. QR Code is today one of the most used code to tag the wares. I show you how to work with the Google's QRCode package (download zxing.jar HERE and core-3.2.1.jar HERE) . For the ease of use I design an API QRCanvas which allows you to create any String to QRCode an print it to a file with the suffix .PNG or .JPG. QRCanvas can be used with SWING. For JavaFX I will soon post the API JfxQRCanvas. Here is the QRCanvas.java
PHP:
import java.io.*;
import java.awt.*;
import java.util.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
// GOOGLE
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;
// Joe Nartca(C)
public class QRCanvas extends Canvas {
  /**
  Constructor
  */
  public QRCanvas( ) {  }
  /**
  load
  @param myString String to be QRCoded
  @param size int, the size of QR Code
  @Exception Exception thrown by Java
  */
  public void load(String myString, int size) throws Exception {
    this.size = size;
    this.myString = myString;
    Map<EncodeHintType, Object> hType = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
    hType.put(EncodeHintType.CHARACTER_SET, "UTF-8");
    // Now with GOOGLE zxing
    hType.put(EncodeHintType.MARGIN, 1);
    hType.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    bitMatrix = qrCodeWriter.encode(myString, BarcodeFormat.QR_CODE, size, size, hType);
    size = bitMatrix.getWidth();
    image = new BufferedImage(size, size, BufferedImage.TYPE_INT_RGB);
    image.createGraphics();
    setSize(size, size);
    preparePaint( );
    repaint( );
  }
  /**
  @param fileName String with suffix .png or jpg
  @Exception Exception thrown by JAVA
  */
  public void printQR(String fileName) throws Exception {
    String ft = fileName.substring(fileName.indexOf(".")+1).toUpperCase();
    if (!"PNG".equals(ft) && !"JPG".equals(ft)) throw new Exception("Unknown FileType:"+fileName);
    ImageIO.write(image, ft, new File(fileName));
  }
  /**
  Overwrite
  */
  public void paint(Graphics g) {
    g.drawImage(image, 0, 0, null);
  }
  /**
  Overwrite
  */
  public void preparePaint( ) {
    Graphics2D g = (Graphics2D) image.getGraphics();
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, size, size);
    g.setColor(Color.BLACK);
    for (int i = 0; i < size; ++i) {
      for (int j = 0; j < size; ++j) {
        if (bitMatrix.get(i, j)) {
          g.fillRect(i, j, 1, 1);
        }
      }
    }
  }
  private BufferedImage image;
  private BitMatrix bitMatrix;
  private String myString;
  private int size;
and how to use it:
PHP:
import javax.swing.*;
// Joe T. Nartca
public class QRCoding extends JFrame {
  public QRCoding( ) {
    setLayout(null);
    setTitle("QRCode in SWING");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JLabel lqr = new JLabel("String to be QRCodes");
    lqr.setBounds(50, 10, 200, 30);
    qr = new JTextField(300);
    qr.setBounds(180, 10, 260, 30);
    qrc = new QRCanvas();
    qrc.setBounds(40, 50, 400, 400);
    JButton go = new JButton(" QR",(Icon) (new ImageIcon(getClass().getResource("QRBut.png"))));
    go.setBounds(270, 460, 150, 80);
    go.addActionListener(e->{
      try {
        qrc.load(qr.getText(), 400);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    });
    JButton print = new JButton("PRINT");
    print.setBounds(150, 460, 100, 80);
    print.addActionListener(e->{
      try {
        String fileName = JOptionPane.showInputDialog("Save QRCode to File.png/File.jpg:");
        if (fileName == null) return;
        qrc.printQR(fileName);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    });
    add(lqr);
    add(qr);
    add(qrc);
    add(go);
    add(print);
    setSize(500, 600);
    setResizable(false);
    setVisible(true);
  }
  private QRCanvas qrc;
  private JTextField qr;
  public static void main(String... args) throws Exception {
    //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    new QRCoding( );
  }
}
and here is the result:
QR_1.png

After input the String "Joe Nartca @ CongdongJava" and click the button with the QRCode symbol you get this image

QR_2.png

It displays the QRCode of the String "Joe Nartca @ CongdongJava". And with the "PRINT" button this QRCode will be saved to the file of any name with the vaild suffix .PNG or .JPG (e.g. joe.png)
 
Sửa lần cuối:
  • Like
Reactions: quydtkt

Joe

Thành viên VIP
21/1/13
2,969
1,311
113
Sorry, I forgot to upload the QRBut.png for download QRBut.png
 

Joe

Thành viên VIP
21/1/13
2,969
1,311
113
To complete the QRCanvas I have implemented the method readQRCode(String qrFileName) so that any QRCoded image can be "decoded" back to a plain string. Insert the following lines into the QRCanvas.java. Note: you need to download this jar file from HERE
PHP:
// GOOGLE
import com.google.zxing.*;
import com.google.zxing.common.*;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
....
  /**
  @param imgFile String, QRCode fileName
  @return String that reflects the QRCode, null if the QRCode file is invalid
  */
  public String readQRCode(String imgFile) {
    try {
      File file = new File(imgFile);
      BufferedImage bufferedImage = ImageIO.read(file);
      LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
      BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
      Result result = new MultiFormatReader().decode(bitmap);
      return result.getText();
    } catch (Exception e) { }
    return null;
  }
  ...
and the QRCoding.java
PHP:
    JButton go = new JButton("QR",(Icon) (new ImageIcon(getClass().getResource("QRBut.png"))));
    go.setBounds(295, 460, 150, 80);
    ...
    JButton print = new JButton("PRINT");
    print.setBounds(175, 460, 100, 80);
   ...
    JButton read = new JButton("READ QRCode");
    read.setBounds(30, 460, 120, 80);
    read.addActionListener(a->{
      String file = qr.getText();
      if (!file.isEmpty()) try {
        String content = qrc.readQRCode(file);
        qrc.load(content, 400);
        JOptionPane.showMessageDialog(jf, "QRCode Content: "+content);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    });
    add(lqr);
    ...
    add(read);
   ...
QR_3.png
 
Sửa lần cuối:
  • Like
Reactions: quydtkt