Java-生成二維碼

zxing方法

zxing是谷歌提供的一個生成而二維碼的庫,這裏使用maven,所以先添加要使用的jar包的座標。

<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>core</artifactId>
  <version>3.2.1</version>
</dependency>
<dependency>
  <groupId>com.google.zxing</groupId>
  <artifactId>javase</artifactId>
  <version>3.0.0</version>
</dependency>

生成二維碼的基本代碼還是比較簡單的。

// 定義要生成二維碼的基本參數
int width = 300;
int height = 300;
String type = "png";
String content = "www.baidu.com";

// 定義二維碼的配置,使用HashMap
HashMap hints = new HashMap();
// 字符集,內容使用的編碼
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 容錯等級,H、L、M、Q
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 邊距,二維碼距離邊的空白寬度
hints.put(EncodeHintType.MARGIN, 2);

try {
    // 生成二維碼對象,傳入參數:內容、碼的類型、寬高、配置
    BitMatrix bitMatrix =  new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
    // 定義一個路徑對象
    Path file = new File("D:/learn/code.png").toPath();
    // 生成二維碼,傳入二維碼對象、生成圖片的格式、生成的路徑
    MatrixToImageWriter.writeToPath(bitMatrix, type, file);
} catch (WriterException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

注意一點,因爲上面的內容我們設置的是www.baidu.com。掃碼結果是這個字符串文本。如果想要掃碼之後直接跳轉到該鏈接,需要在網址前面加上協議http://www.baidu.com

既然有生成的方法,就有對應的解析二維碼的方法。解析二維碼就有些繁瑣了。

try {
    // 聲明一個解析二維碼的對象
    MultiFormatReader formatReader = new MultiFormatReader();
    // 生成一個文件對象,傳入剛纔生成二維碼的路徑
    File file = new File("D:/learn/code.png");
    // 把文件對象轉成一個圖片對象
    BufferedImage image = ImageIO.read(file);
    // 最後需要的是一個binaryBitmap對象。
    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
    // 配置,解析時傳入
    HashMap hints = new HashMap();
    hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
    // 解析得到一個Result對象,該對象包含二維碼的信息
    Result result = formatReader.decode(binaryBitmap, hints);
    // 分別輸出二維碼類型和內容的方法
    System.out.println(result.getBarcodeFormat());
    System.out.println(result.getText());
} catch (IOException e) {
    e.printStackTrace();
} catch (NotFoundException e) {
    e.printStackTrace();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章