First add the version Maven dependency
<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.3.0</version> </dependency>
The jar package relied on here is mainly Google’s zxing for QR code generation
Code
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode("我是", BarcodeFormat.QR_CODE, 600, 600);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
Base64.Encoder encoder = Base64.getEncoder();
String text = encoder.encodeToString(outputStream.toByteArray()); System.out.println("data:image/png;base64"+text);
Note: The content that needs to be displayed in the QR code is the string 622921
The parameter 600*600 represents the width and height of the QR code after generation, in px pixels
Here we are using the base64 encoding generated by Java's own Base64 tool class
The generated base64 is as follows
View Code
Note: The encoded base64 string here does not have the format characters used when the front-end img tag is parsed. It needs to be spliced before the string: data:image/png;base64,
It can be displayed normally! !
test
Online verification: http://imgbase64.duoshitong.com/
Effect: After scanning the code on WeChat, the result is: 622921
Local generation scheme
It can be realized by only modifying part of the key code, and writing to the disk by way of byte stream. Here, the file object is directly manipulated by byte stream, and there is no need to close the stream.
File file = new File("H:/test/456.png");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream outputStream = new FileOutputStream(file);
MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);