Java生成二维码
Maven依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.5.0</version>
</dependency>
生成二维码
public static void generateQRCodeImage(String text, int width, int height, String filePath, HashMap hints)
throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
解析二维码
public static void parseQRCodeImage(String filePath,HashMap hints)
throws NotFoundException, IOException, ChecksumException, FormatException {
QRCodeReader qrCodeReader = new QRCodeReader();
File file = new File(filePath);
BufferedImage bufferedImage = ImageIO.read(file);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer = new HybridBinarizer(luminanceSource);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Result result = qrCodeReader.decode(binaryBitmap);
System.out.println(result.getText());
}
Main方法
public static void main(String[] args) {
int width = 400;
int height = 400;
String format = "png";
String content = "https://www.baidu.com";
String filePath = "E:/dev/test.png";
HashMap<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//L 水平 7%的字码可被修正
//M 水平 15%的字码可被修正
//Q 水平 25%的字码可被修正
//H 水平 30%的字码可被修正
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
try {
generateQRCodeImage(content, width, height, filePath, hints);
parseQRCodeImage(filePath,hints);
} catch (WriterException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ChecksumException e) {
throw new RuntimeException(e);
} catch (NotFoundException e) {
throw new RuntimeException(e);
} catch (FormatException e) {
throw new RuntimeException(e);
}
}
Controller方法
@Controller
@RequestMapping("qr")
public class QrController {
@RequestMapping
public void createQrCode(HttpServletResponse response) throws WriterException, IOException {
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);
BitMatrix bitMatrix = new QRCodeWriter().encode("content", BarcodeFormat.QR_CODE, 200, 200, hints);
MatrixToImageWriter.writeToStream(bitMatrix, "png", response.getOutputStream());
}
}