引入依赖
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
编写工具类
public class QRCodeUtil {
private static int width = 400;
private static int height = 400;
private static String format = "png";
public static String encodeQRCode(String text) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String result = null;
try {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
bitMatrix.clear();
result = "data:image/png;base64," + Base64.getEncoder().encodeToString(outputStream.toByteArray());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
}
}
return result;
}
public static String decodeQRCode(String base64) {
Result result = null;
BufferedImage image = null;
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(base64));
try {
image = ImageIO.read(inputStream);
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, String> hints = new HashMap<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
result = new MultiFormatReader().decode(binaryBitmap, hints);
} catch (Exception e) {
System.out.println(e);
} finally {
image.getGraphics().dispose();
try {
inputStream.close();
} catch (IOException e) {
}
}
return result.getText();
}
}
测试
public static void main(String[] args) {
System.out.println(encodeQRCode("我叫XX勇~~~"));
System.out.println(decodeQRCode("xxxxxxxxxx.....xxxxxxxx"));
}