Google Zxing 二維碼生成與解析

    生成二維碼的開源項目可謂是琳琅滿目,SwetakeQRCode、BarCode4j、Zxing......前端

    前端有JQuery-qrcode,一樣能實現生成二維碼。java

    選擇Zxing的緣由多是對 Google 公司的信賴和我的崇拜吧。dom

    其實使用起來至關的簡單,我這裏使用的是最新3.2 Zxing.jar ,省的你找jar的時間,下面是下載地址。spa

    百度雲盤地址:http://pan.baidu.com/s/1c0VXMPa   提取密碼: bssvcode

    生成二維碼:orm

    public static String createQrcode(String _text){
        String qrcodeFilePath = "";
        try {
            int qrcodeWidth = 300;
            int qrcodeHeight = 300;
            String qrcodeFormat = "png";
            HashMap<EncodeHintType, String> hints = new HashMap<EncodeHintType, String>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            BitMatrix bitMatrix = new MultiFormatWriter().encode('http://www.cnblogs.com/java-class/', BarcodeFormat.QR_CODE, qrcodeWidth, qrcodeHeight, hints);

            BufferedImage image = new BufferedImage(qrcodeWidth, qrcodeHeight, BufferedImage.TYPE_INT_RGB);
            Random random = new Random();
            File QrcodeFile = new File("F:\\qrcode\\" + random.nextInt() + "." + qrcodeFormat);
            ImageIO.write(image, qrcodeFormat, QrcodeFile);
            MatrixToImageWriter.writeToFile(bitMatrix, qrcodeFormat, QrcodeFile);
            qrcodeFilePath = QrcodeFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrcodeFilePath;
    }

   a.上述代碼中的 hints,爲生成二維碼時的一些參數設置,實現者將它構建Map類型的參數。對象

   b.上述生成實現當中,每生成一個二維碼都會存放在目錄下面,名稱取整數隨機數。blog

   c. MultiFormatWriter 對象爲生成二維碼的核心類,後面的 MatrixToImageWriter 只是將二維碼矩陣輸出到圖片上面。圖片

   解析二維碼:get

   public static String decodeQr(String filePath) {
        String retStr = "";
        if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
            return "圖片路徑爲空!";
        }
        try {
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filePath));
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            Binarizer binarizer = new HybridBinarizer(source);
            BinaryBitmap bitmap = new BinaryBitmap(binarizer);
            HashMap<DecodeHintType, Object> hintTypeObjectHashMap = new HashMap<>();
            hintTypeObjectHashMap.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, hintTypeObjectHashMap);
            retStr = result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }

   a.讀取二維碼圖片,並送給 Zxing LuminanceSource 和 Binarizer 兩兄弟的處理。

   b.處理完的位圖和相應的解析參數,交由 MultiFormatReader 處理,並返回解析後的結果。

   c.若是對上述 兩兄弟的處理 和 MultiFormatReader  的解析有興趣,能夠讀讀源碼。

相關文章
相關標籤/搜索