Java實現二維碼QRCode的編碼和解碼

週末試用下Android手機的二維碼掃描軟件,掃描了下火車票、名片等等,覺得非常不錯很有意思的。當然Java也可以實現這些,現在就分享下如何簡單用Java實現二維碼中QRCode的編碼和解碼(可以手機掃描驗證)。

 

    涉及到的一些主要類庫,方便大家下載

編碼lib:Qrcode_swetake.jar   (官網介紹-- http://www.swetake.com/qr/index-e.html)             

解碼lib:qrcode.jar                 (官網介紹-- http://sourceforge.jp/projects/qrcode/)

 

【一】、編碼:

QRCodeEncoderHandler.java

Java代碼 

package michael.qrcode; 

 

import java.awt.Color; 

import java.awt.Graphics2D; 

import java.awt.image.BufferedImage; 

import java.io.File; 

 

import javax.imageio.ImageIO; 

 

import com.swetake.util.Qrcode; 

 

/**

 * 二維碼生成器

 * @blog http://sjsky.iteye.com

 * @author Michael

 */ 

public class QRCodeEncoderHandler { 

 

    /**

     * 生成二維碼(QRCode)圖片

     * @param content

     * @param imgPath

     */ 

    public void encoderQRCode(String content, String imgPath) { 

        try { 

 

            Qrcode qrcodeHandler = new Qrcode(); 

            qrcodeHandler.setQrcodeErrorCorrect('M'); 

            qrcodeHandler.setQrcodeEncodeMode('B'); 

            qrcodeHandler.setQrcodeVersion(7); 

 

            System.out.println(content); 

            byte[] contentBytes = content.getBytes("gb2312"); 

 

            BufferedImage bufImg = new BufferedImage(140, 140, 

                    BufferedImage.TYPE_INT_RGB); 

 

            Graphics2D gs = bufImg.createGraphics(); 

 

            gs.setBackground(Color.WHITE); 

            gs.clearRect(0, 0, 140, 140); 

 

            // 設定圖像顏色> BLACK 

            gs.setColor(Color.BLACK); 

 

            // 設置偏移量 不設置可能導致解析出錯 

            int pixoff = 2; 

            // 輸出內容> 二維碼 

            if (contentBytes.length > 0 && contentBytes.length < 120) { 

                boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes); 

                for (int i = 0; i < codeOut.length; i++) { 

                    for (int j = 0; j < codeOut.length; j++) { 

                        if (codeOut[j][i]) { 

                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3); 

                        } 

                    } 

                } 

            } else { 

                System.err.println("QRCode content bytes length = " 

                        + contentBytes.length + " not in [ 0,120 ]. "); 

            } 

 

            gs.dispose(); 

            bufImg.flush(); 

 

            File imgFile = new File(imgPath); 

 

            // 生成二維碼QRCode圖片 

            ImageIO.write(bufImg, "png", imgFile); 

 

        } catch (Exception e) { 

            e.printStackTrace(); 

        } 

 

    } 

 

    /**

     * @param args the command line arguments

     */ 

    public static void main(String[] args) { 

        String imgPath = "D:/test/twocode/Michael_QRCode.png"; 

 

        String content = "Hello 大大、小小,welcome to QRCode!" 

                + "\nMyblog [ http://sjsky.iteye.com ]" 

                + "\nEMail [ [email protected] ]" + "\nTwitter [ @suncto ]"; 

 

        QRCodeEncoderHandler handler = new QRCodeEncoderHandler(); 

        handler.encoderQRCode(content, imgPath); 

 

        System.out.println("encoder QRcode success"); 

    } 

 

   運行後生成的二維碼圖片如下:

                                      

 

 

此時就可用手機的二維碼掃描軟件(本人用的:android 快拍二維碼 )來測試下,識別成功的截圖如下:

 

喜歡的朋友可以下載後試一試,做一些名片或者自己喜歡的東西。當然Java也可以對二維碼圖片解碼,具體看下面關於解碼的內容。

 

 

【二】、解碼:

 QRCodeDecoderHandler.java

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); 

        } 

 

    } 

 

運行結果如下(解碼出的內容和之前輸入的內容一致 ):

解析結果如下:

Hello 大大、小小,welcome to QRCode!

Myblog [ http://sjsky.iteye.com ]

EMail [ [email protected] ]

Twitter [ @suncto ]

========decoder success!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章