前端页面(html导入了vue):
步骤一:前端页面就弄个img 给src绑定一个属性
<div><img :src="qrCodeImage" alt="二维码图片"></div>
在data数据写入上面img绑定的一个属性
data(){
return {
userId:23,
code:"", //动态生成推荐链接
qrCodeImage: "", // 用于存储Base64编码的图片数据
//数据统计
orderNumber:10,
courseNumber:10,
collectNumber:10,
commentNumber:10,
courseList:[]
}
}
在methods方法写一个方法,将data中的数据写入,如下:
code是验证码,userID是当前用户的ID,可以根据具体情况改变
将参数通过post请求调到后端,后端返回的数据拼接data:image/png;base64生成二维码
QRcode(){
var param = {
code: this.code,
userId: this.userId
};
this.$http.post("/user/userCode/generateQRCode",param).then(res=>{
var ajaxResult = res.data;
console.log(ajaxResult);
this.qrCodeImage = "data:image/png;base64," + res.data;
}).catch(error => {
$.alert("加载失败");
});
}
后端代码(java)
后端接收到前端发的POST请求,然后拼接url地址+验证码,设置好宽度、高度
需要用到配置类,在下面提供了
@RequestMapping(value = "/generateQRCode",method = RequestMethod.POST)
public String QRcode(@RequestBody UserCode userCode) throws IOException {
UserCode userCode2 = new UserCode();
userCode.setId(23l);
UserCode existingUserCode = userCodeMapper.selectOne(userCode2);
System.out.println(existingUserCode);
// 这里根据您的前端生成链接的方式,将URL拼接好
String url = "http://localhost:6003/reg.phone.html?code=" + existingUserCode.getCode();
int width = 100; // 宽度
int height = 100; // 高度
byte[] qrCodeBytes = QRCodeGenerator.generateQRCode(url, width, height);
// 将字节数组转换为Base64编码字符串
return Base64.getEncoder().encodeToString(qrCodeBytes);
}
配置类:
public class QRCodeGenerator {
public static byte[] generateQRCode(String url, int width, int height) throws IOException {
try {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
Writer writer = new QRCodeWriter();
BitMatrix bitMatrix = writer.encode(url, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int color = bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF;
image.setRGB(x, y, color);
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "png", baos);
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
需要用到的依赖:
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.1</version>
</dependency>
转载链接 :https://blog.csdn.net/CC805034104/article/details/132194288
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/CC805034104/article/details/132194288