1.什么是二維碼?
(百度百科):二維碼又稱二維條碼,常見的二維碼為QR Code,QR全稱Quick Response,是一個近幾年來移動設備上超流行的一種編碼方式,它比傳統的Bar Code條形碼能存更多的信息,也能表示更多的數據類型。
2.利用ZXING生成二維碼
·對應POM
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.1</version>
</dependency>
·Java代碼(生成二維碼)
// 二維碼的寬度
static final int WIDTH = 300; // 二維碼的高度
static final int HEIGHT = 300; // 二維碼的格式
static final String FORMAT = "png"; // 二維碼的內容
static final String TEXT = "Hello!二維碼!!!"; /** * 生成二維碼 */ @Test public void generate() { /* 定義二維碼的參數 */ HashMap hashMap = new HashMap(); // 設置二維碼字符編碼
hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 設置二維碼糾錯等級
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); // 設置二維碼邊距
hashMap.put(EncodeHintType.MARGIN, 2); try { // 開始生成二維碼
BitMatrix bitMatrix = new MultiFormatWriter().encode(TEXT, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hashMap); // 導出到指定目錄
MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, new File("D://erweima.png").toPath()); } catch (WriterException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
生成出來的二維碼!!!
·Java代碼(讀取二維碼)
/** * 讀取二維碼 */ @Test public void read() throws IOException, NotFoundException { // 讀取二維碼為圖片
BufferedImage bufferedImage = ImageIO.read(new File("D://erweima.png")); // 獲取二維碼的結果
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage))); /* 定義二維碼的參數 */ HashMap hashMap = new HashMap(); // 設置二維碼字符編碼
hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 對圖像進行解碼
Result result = new MultiFormatReader().decode(binaryBitmap, hashMap); System.out.println("解析二維碼的內容是:" + result.getText()); }
讀取二維碼里面的內容!!!