maven jar包依賴
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
生成二維碼
public static void encode(File file, String content, String format) throws IOException, WriterException {
// 設置生成的二維碼的高度和寬度
int height = 500, width = 500;
// 編碼時的額外參數
Map hints = Maps.newHashMap();
// 編碼
hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.displayName());
// 容錯等級
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
// 邊框
hints.put(EncodeHintType.MARGIN, 2);
// 編碼的方式(二維碼、條形碼...)
BarcodeFormat qrCode = BarcodeFormat.QR_CODE;
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, qrCode, width, height, hints);
MatrixToImageWriter.writeToPath(bitMatrix, format, file.toPath());
}
生成帶logo 的二維碼
public static void encode(File file, String content, File logoImg) throws IOException, WriterException {
String fileName = file.getName();
String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
encode(file, content, fileType);
BufferedImage logo = ImageIO.read(file);
overlapImage(logo, fileType, file, logoImg);
}
識別二維碼
public static String decode(File file) throws IOException, NotFoundException {
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
Map hints = Maps.newHashMap();
hints.put(EncodeHintType.CHARACTER_SET, StandardCharsets.UTF_8.displayName());
Result result = formatReader.decode(binaryBitmap, hints);
// 種類: result.getBarcodeFormat()
return result.getText();
}