小程序解析二维码:jsQR

时间:2024-04-10 09:29:23
// index.js import jsQR from "jsqr"; Page({ data: { msg: "", canvasWidth: 0, canvasHeight: 0, }, chooseImage() { wx.vibrateShort(); wx.chooseMedia({ count: 1, mediaType: ["image"], sourceType: ["album", "camera"], success: (res) => { this.decodeQRCode(res.tempFiles[0].tempFilePath); }, fail: (err) => { console.error("选择图片失败", err); }, }); }, decodeQRCode(imagePath) { wx.getImageInfo({ src: imagePath, success: (imageInfo) => { this.setData({ canvasWidth: imageInfo.width, canvasHeight: imageInfo.height, }); const canvasId = "qrcodeCanvas"; const ctx = wx.createCanvasContext(canvasId); ctx.drawImage(imagePath, 0, 0, imageInfo.width, imageInfo.height); ctx.draw(); }, fail: (err) => { console.error("获取图片信息失败", err); }, }); }, process() { const imageInfo = { width: this.data.canvasWidth, height: this.data.canvasHeight, }; wx.canvasGetImageData({ canvasId: "qrcodeCanvas", x: 0, y: 0, width: imageInfo.width, height: imageInfo.height, success: (res) => { console.log(res); const imageData = { data: res.data, width: imageInfo.width, height: imageInfo.height, }; // console.log( // "识别前的数据", // imageData.data, // imageData.width, // imageData.height // ); const decodedResult = jsQR( imageData.data, imageData.width, imageData.height, { inversionAttempts: "dontInvert", } ); console.log("结果", decodedResult); if (decodedResult) { console.log(decodedResult.data); // 识别结果 this.setData({ msg: decodedResult.data, }); } else { wx.showToast({ icon: "none", title: "未识别到二维码!", }); } }, fail: (err) => { console.error("获取 Canvas 像素数据失败", err); }, }); }, });