Java实现生成二维码
1.引入谷歌提供jar包
2.后台service层代码:
public BufferedImage coachQRCode(Long coachId) throws WriterException {
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
//二维码中返回数据
CoachQRDto qr = new CoachQRDto();
qr.setCoachId(coachId);
//3分钟过期时间
qr.setExpireTime(Dates.addMinute(new Date(),3).getTime());
//根据实际业务编写
// BitMatrix qrcode = new QRCodeWriter().encode(Jsons.toJSONString(qr), BarcodeFormat.QR_CODE, 300, 300);
//可直接写入网址扫码即可跳转页面
BitMatrix qrcode = new QRCodeWriter().encode("https://www.baidu.com", BarcodeFormat.QR_CODE, 300, 300);
return MatrixToImageWriter.toBufferedImage(qrcode);
}
3.controller层代码
@GetMapping(value = "/coachQRCode", produces = MediaType.IMAGE_JPEG_VALUE)
public BufferedImage coachQRCode(Long coachId) throws WriterException {
return bizCoachService.coachQRCode(coachId);
}
4.postman调用结果:
前端获取
写入地址即可。注意请加上协议及完整地址