使用zxing生成二维码
引入zxing依赖库:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
生成二维码:
@Test
public void encode() {
final int width = 300;
final int height = 300;
final String format = "png";
String content = "com.tim.test.qrcode";
final Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try {
final BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToPath(matrix,format,new File("D:/my.png").toPath());
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
解析二维码:
@Test
public void decode() {
final MultiFormatReader reader = new MultiFormatReader();
File image = new File("D:/my.png");
try {
final BufferedImage bufferedImage = ImageIO.read(image);
final BinaryBitmap binaryBitmap = new BinaryBitmap(
new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
final Map hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
final Result result = reader.decode(binaryBitmap, hints);
System.out.println(result.getText());
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}