第一步, 加入pom。
<!-- 二维码 -->
<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>
第二步,在service接口中写入二维码配置信息
// 二维码长 , 宽 , 生成图片格式
int QR_WIDTH = 400;
int QR_HEIGH = 400;
String QR_FORMAT = "PNG";
String URL = "https://xxxxxxxxxx/miniprogram/?pile_id=";
//获取二维码流
OutputStream getQRcode(String tcomid) throws Exception;
//获取二维码base64
String getQRcodeBase64(String tcomid) throws Exception;
第三步,在serviceImpl中实现service中的接口。
//获取二维码流
@Override
public OutputStream getQRcode(String tcomid) throws Exception {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(URL + tcomid, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGH);
ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, QR_FORMAT, pngOutputStream);
return pngOutputStream;
}
//获取base64格式的二维码
@Override
public String getQRcodeBase64(String tcomid) throws Exception {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(URL + tcomid, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGH);
Path path = Paths.get("./", QR_FORMAT);
MatrixToImageWriter.writeToPath(bitMatrix, QR_FORMAT, path);
File file = path.toFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream inputFile = new FileInputStream(file);
byte[] buffer = new byte[(int) file.length()];
int n;
while ((n = inputFile.read(buffer)) != -1) {
bos.write(buffer, 0, n);
}
buffer = bos.toByteArray();
String imageBase64 = Base64.getEncoder().encodeToString(buffer);
inputFile.close();
if (file.exists()) {
file.deleteOnExit();
}
return imageBase64;
}
第四步,在Controller层中写接口。
//获取二维码接口 返回base64格式
@GetMapping(value = "/QRcode")
public ResponseResult QRcode(@RequestParam(required = false) Map<String, Object> paraMap , HttpServletResponse response)
{
String pile_id = paraMap.get("pile_id").toString();
//此处的查询可以根据具体情况修改
PileCharge pileCharge = service.queryById(pile_id);
if(pileCharge == null)
{
return ResponseResult.ok(I18nUtil.getMessageDefault("pileCharge.noHas", "充电桩不存在"));
}
String qr = null;
try {
qr = service.getQRcodeBase64(pileCharge.getTcomid());
}catch (Exception e) {
return ResponseResult.ok(I18nUtil.getMessageDefault("QR.generate.fail", "二维码生成失败,请稍后重试"));
}
Map<String , Object> map = new HashMap();
map.put("QRpng" , qr);
return ResponseResult.ok(map);
}