java生成二维码并解决中文乱码问题,小程序扫码识别二维码
1.java生成二维码并解决中文乱码问题
添加Zxing的依赖(maven工程为例)
<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>
保存信息为二维码图片
获取当前用户的桌面路径,生成图片存放在桌面。
package org.thinkingingis.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
public class QRCodeGenerator {
private static final String QR_CODE_IMAGE_PATH_TAIL = "_QRCode.png";
private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
//!!!此处解决中文乱码问题
HashMap<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//保存信息为二维码图片
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath);
//生成图片存放在路径上
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
public static void main(String[] args) {
//获取当前用户的桌面路径
String qrCodeImagePathPre = FileSystemView.getFileSystemView().getHomeDirectory().getPath() + "/";
String deptId= “a1001”;
String deptName = “医务科”;
Map<String, String> map = new HashMap<String, String>();
map.put("deptId", deptId);
map.put("deptName", deptName);
//将map转为字符串
String json = JSONObject.toJSONString(map);
try {
generateQRCodeImage(json, 350, 350, qrCodeImagePathPre + deptName + QR_CODE_IMAGE_PATH_TAIL);
} catch (WriterException e) {
System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());
} catch (IOException e) {
System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());
}
}
}
2.小程序扫码识别二维码
QRCodeCheck: function (e) {
/** 扫码事件**/
var that = this;
wx.scanCode({
onlyFromCamera: true,// 只允许从相机扫码
success(res){
console.log("扫码成功:"+ res.result);
//将字符串转为json对象
var dept = JSON.parse(res.result);
// 扫码成功后 在此处理接下来的逻辑
that.setData({
scanCode: res.result//扫描得到的结果
})
this.query();//接下来处理的事件
},
fail (err) {
console.log("扫码失败:"+ JSON.stringify(err))
wx.showToast({
title:'扫描失败',
icon: 'none',
duration: 1000
})
// 扫码失败后 在此处理接下来的逻辑
that.setData({
scanCode: '',c:0,cc:0,ccc:0,t:0
})
}
})
}