天天看點

二維碼功能實作簡單例子

//所需jar包下載下傳位址:http://download.csdn.net/download/huchgu/9996818

//二維碼示範實作類,支援中文無亂碼,在項目中導入所需jar即可運作

public class QrcodeDemo {  

    public static void main(String[] args) {

        String str = "https://github.com/zxing/zxing";  //二維碼内容

        String path = "E:/test.png";                               //二維碼圖檔生成路徑

        QrcodeDemo t = new QrcodeDemo();          //執行個體化示範類

        t.encode(str, path,400,400);                            //生成二維碼圖檔

        String res = t.decode(path);                            //根據傳入的2維碼圖檔所在路徑,解析得到二維碼圖檔裡的内容

        System.out.println("解碼結果:"+res);          //列印掃描結果

    }  

    public void encode(String str, String path,int width,int height) {  

        try {  

            BitMatrix byteMatrix = new MultiFormatWriter()

            .encode(str, BarcodeFormat.QR_CODE, width, height);  //後兩個參數設定二維碼圖檔大小-圖檔像素大小 

            File file = new File(path);                                                         //建立矩陣檔案  

            MatrixToImageWriter.writeToFile(byteMatrix, "gif", file);     //将矩陣檔案轉換成圖檔檔案  

        } catch (Exception e) {  

            e.printStackTrace();

        }  

    }  

    public String decode(String imgPath) {  

         try {  

              File file = new File(imgPath);                           //擷取該圖檔檔案  

              BufferedImage image = ImageIO.read(file);

              if (image != null) {

        LuminanceSource source = new BufferedImageLuminanceSource(image);  

                   BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));  

                   Hashtable hashtable = new Hashtable();                                      //将圖檔反解碼為二維矩陣  

                   hashtable.put(DecodeHintType.CHARACTER_SET, "UTF-8");  

                   Result result = new MultiFormatReader().decode(bitmap, hashtable);  //将該二維矩陣解碼成内容  

                   return result.getText();

              }

         } catch (Exception e) {  

    e.printStackTrace();

         }

         return null;

    }  

}