Java生成二维码
一、导入的依赖Google Zxing
<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 createAndSpawnQRCode(String content, OutputStream outputStream) throws IOException {
int width = 200;
int height = 200;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.ERROR_CORRECTION , ErrorCorrectionLevel.H);
hints.put(EncodeHintType.MARGIN , 0);
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , outputStream);
}
三、具体实现
public void QRCode() {
String path = "src/main/resources/Jpg";
String fileName = "生产的二维码.jpg";
String name = path + fileName;
String Url = "www.baidu.com";
try (OutputStream outputStream = new FileOutputStream(name)) {
QRCodeUtil.createAndSpawnQRCode(Url,outputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}