Java实现二维码QRCode的编码和解码

转:http://blog.csdn.net/ljb_blog/article/details/6700834

【一】、编码:

QRCodeEncoderHandler.java

 1 package michael.qrcode;
 2 
 3 import java.awt.Color;
 4 import java.awt.Graphics2D;
 5 import java.awt.image.BufferedImage;
 6 import java.io.File;
 7 
 8 import javax.imageio.ImageIO;
 9 
10 import com.swetake.util.Qrcode;
11 
12 /**
13  * 二维码生成器
14  * @blog http://sjsky.iteye.com
15  * @author Michael
16  */
17 public class QRCodeEncoderHandler {
18 
19     /**
20      * 生成二维码(QRCode)图片
21      * @param content
22      * @param imgPath
23      */
24     public void encoderQRCode(String content, String imgPath) {
25         try {
26 
27             Qrcode qrcodeHandler = new Qrcode();
28             qrcodeHandler.setQrcodeErrorCorrect('M');
29             qrcodeHandler.setQrcodeEncodeMode('B');
30             qrcodeHandler.setQrcodeVersion(7);
31 
32             System.out.println(content);
33             byte[] contentBytes = content.getBytes("gb2312");
34 
35             BufferedImage bufImg = new BufferedImage(140, 140,
36                     BufferedImage.TYPE_INT_RGB);
37 
38             Graphics2D gs = bufImg.createGraphics();
39 
40             gs.setBackground(Color.WHITE);
41             gs.clearRect(0, 0, 140, 140);
42 
43             // 设定图像颜色 > BLACK
44             gs.setColor(Color.BLACK);
45 
46             // 设置偏移量 不设置可能导致解析出错
47             int pixoff = 2;
48             // 输出内容 > 二维码
49             if (contentBytes.length > 0 && contentBytes.length < 120) {
50                 boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
51                 for (int i = 0; i < codeOut.length; i++) {
52                     for (int j = 0; j < codeOut.length; j++) {
53                         if (codeOut[j][i]) {
54                             gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
55                         }
56                     }
57                 }
58             } else {
59                 System.err.println("QRCode content bytes length = "
60                         + contentBytes.length + " not in [ 0,120 ]. ");
61             }
62 
63             gs.dispose();
64             bufImg.flush();
65 
66             File imgFile = new File(imgPath);
67 
68             // 生成二维码QRCode图片
69             ImageIO.write(bufImg, "png", imgFile);
70 
71         } catch (Exception e) {
72             e.printStackTrace();
73         }
74 
75     }
76 
77     /**
78      * @param args the command line arguments
79      */
80     public static void main(String[] args) {
81         String imgPath = "D:/test/twocode/Michael_QRCode.png";
82 
83         String content = "Hello 大大、小小,welcome to QRCode!"
84                 + "
Myblog [ http://sjsky.iteye.com ]"
85                 + "
EMail [ sjsky007@gmail.com ]" + "
Twitter [ @suncto ]";
86 
87         QRCodeEncoderHandler handler = new QRCodeEncoderHandler();
88         handler.encoderQRCode(content, imgPath);
89 
90         System.out.println("encoder QRcode success");
91     }
92 }

【二】、解码: 
 QRCodeDecoderHandler.java

package michael.qrcode;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

/**
 * @blog http://sjsky.iteye.com
 * @author Michael
 */
public class QRCodeDecoderHandler {

    /**
     * 解码二维码
     * @param imgPath
     * @return String
     */
    public String decoderQRCode(String imgPath) {

        // QRCode 二维码图片的文件
        File imageFile = new File(imgPath);

        BufferedImage bufImg = null;
        String decodedData = null;
        try {
            bufImg = ImageIO.read(imageFile);

            QRCodeDecoder decoder = new QRCodeDecoder();
            decodedData = new String(decoder.decode(new J2SEImage(bufImg)));

            // try {
            // System.out.println(new String(decodedData.getBytes("gb2312"),
            // "gb2312"));
            // } catch (Exception e) {
            // // TODO: handle exception
            // }
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
            e.printStackTrace();
        } catch (DecodingFailedException dfe) {
            System.out.println("Error: " + dfe.getMessage());
            dfe.printStackTrace();
        }
        return decodedData;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        QRCodeDecoderHandler handler = new QRCodeDecoderHandler();
        String imgPath = "d:/test/twocode/Michael_QRCode.png";
        String decoderContent = handler.decoderQRCode(imgPath);
        System.out.println("解析结果如下:");
        System.out.println(decoderContent);
        System.out.println("========decoder success!!!");
    }

    class J2SEImage implements QRCodeImage {
        BufferedImage bufImg;

        public J2SEImage(BufferedImage bufImg) {
            this.bufImg = bufImg;
        }

        public int getWidth() {
            return bufImg.getWidth();
        }

        public int getHeight() {
            return bufImg.getHeight();
        }

        public int getPixel(int x, int y) {
            return bufImg.getRGB(x, y);
        }

    }
}

  

原文地址:https://www.cnblogs.com/ghostTao/p/4161203.html