js生成二维码和解析二维码
这个整了好久,用的包换了好几次,所以记录一下
生成二维码
<div class="container"><div class="row"><div class="col-md-6 mx-auto my-5"><form class="text-center"><div class="form-group"><label for="message">Enter message:</label><textarea class="form-control" id="message" name="message" rows="5" placeholder="Type your message here"></textarea></div><button type="button" class="btn btn-primary" onclick="generateQRCode()">Generate QR Code</button></form><div id="qrcode" class="mt-4"></div></div></div></div><script src="/js/qrcode.min.js"></script><script>function generateQRCode() {var message = document.getElementById("message").value;var qrcode = new QRCode(document.getElementById("qrcode"), {text: message,width: 256,height: 256,colorDark: "#000000",colorLight: "#ffffff",correctLevel: QRCode.CorrectLevel.H});}</script>
解析二维码
<div class="container"><div class="row"><div class="col-md-6 mx-auto my-5"><form class="text-center"><input type="file" id="uploadInput" accept="image/*"></form><div id="result"></div></form><div id="qrcode" class="mt-4"></div></div></div></div><script src="js/reqrcode.js"></script><script>const form = document.getElementById('uploadForm');const input = document.getElementById('uploadInput');input.onchange = function () {// files[0]是通过input file上传的二维码图片文件qrcode.decode(getObjectURL(this.files[0]));qrcode.callback = function (imgMsg) {//imgMsg 就是解析后的路径document.getElementById('result').innerText = decodeStr(imgMsg);}}//获取预览图片路径var getObjectURL = function (file) {let url = null;if (window.createObjectURL != undefined) { // basicurl = window.createObjectURL(file);} else if (window.URL != undefined) { // mozilla(firefox)url = window.URL.createObjectURL(file);} else if (window.webkitURL != undefined) { // webkit or chromeurl = window.webkitURL.createObjectURL(file);}return url;}function decodeStr(str) {var out, i, len, c;var char2, char3;out = "";len = str.length;i = 0;while (i < len) {c = str.charCodeAt(i++);switch (c >> 4) {case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:// 0xxxxxxxout += str.charAt(i - 1);break;case 12:case 13:// 110x xxxx 10xx xxxxchar2 = str.charCodeAt(i++);out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));break;case 14:// 1110 xxxx 10xx xxxx 10xx xxxxchar2 = str.charCodeAt(i++);char3 = str.charCodeAt(i++);out += String.fromCharCode(((c & 0x0F) << 12) |((char2 & 0x3F) << 6) |((char3 & 0x3F) << 0));break;}}return out;}</script>
然后是两个引入的js
reqrcode和qrcode