java和js生成二维码
1. java生成二维码
1.1 依赖jar包配置(使用maven依赖)
1 <dependency> 2 <groupId>com.google.zxing</groupId> 3 <artifactId>core</artifactId> 4 <version>3.0.0</version> 5 </dependency> 6 <dependency> 7 <groupId>com.google.zxing</groupId> 8 <artifactId>javase</artifactId> 9 <version>3.0.0</version> 10 </dependency>
1.2 生成二维码——Zxing
1 public static void createQrCode() { 2 try { 3 String content = "120605181003;http://www.cnblogs.com/jtmjx"; 4 String path = "D:/temp"; 5 6 MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); 7 8 Map hints = new HashMap(); 9 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 10 BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 400, 400, hints); 11 File file1 = new File(path, "qrCode.jpg"); 12 MatrixToImageWriter.writeToFile(bitMatrix, "jpg", file1); 13 14 System.out.println("成功生成二维码"); 15 } catch (Exception e) { 16 e.printStackTrace(); 17 } 18 }
1.3 解析二维码——Zxing
1 public static void parseQrCode() { 2 try { 3 MultiFormatReader formatReader = new MultiFormatReader(); 4 String filePath = "D:/temp/qrCode.jpg"; 5 File file = new File(filePath); 6 BufferedImage image = ImageIO.read(file); 7 ; 8 LuminanceSource source = new BufferedImageLuminanceSource(image); 9 Binarizer binarizer = new HybridBinarizer(source); 10 BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); 11 Map hints = new HashMap(); 12 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); 13 Result result = formatReader.decode(binaryBitmap, hints); 14 15 System.out.println("result = " + result.toString()); 16 System.out.println("resultFormat = " + result.getBarcodeFormat()); 17 System.out.println("resultText = " + result.getText()); 18 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 }
2. js生成二维码
2.1 使用jquery-qrcode
jquery-qrcode特点:操作简单,体积小,压缩之后只有14k,但是不支持中文编码。
jquery.qrcode.min.js文件下载路径:https://files.cnblogs.com/files/qdwyg2013/jquery.qrcode.min.js
1 <script type="text/javascript" src="http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script> 2 <script type="text/javascript" src="../js/jquery.qrcode.min.js"></script> 3 <script> 4 // 方式一 5 //$('#qrcode').qrcode("http://www.cnblogs.com/xiyangbaixue"); 6 // 方式二 7 $("#qrcode").qrcode({ 8 render: "table", //table方式 9 width: 200, //宽度 10 height:200, //高度 11 text: "www.baidu.com" //任意内容 12 }); 13 </script>
2.2 使用qrcode
qrcode特点:中文生成的二维码扫描不会出现乱码,且可以选择使用哪种元素来画二维码。
qrcode.js文件下载路径:https://files.cnblogs.com/files/qdwyg2013/qrcode.js
1 <script type="text/javascript" src="http://cdn.staticfile.org/jquery/2.0.0/jquery.min.js"></script> 2 <script type="text/javascript" src="../js/qrcode.js"></script> 3 <script> 4 // 方式一 5 //new QRCode(document.getElementById("qrcode"), "http://www.cnblogs.com/xiyangbaixue"); 6 // 方式二 7 new QRCode(document.getElementById("qrcode"), { 8 text: "http://www.cnblogs.com/xiyangbaixue", 9 width: 50, 10 height: 50, 11 background: "#ccc", 12 foreground: "red" 13 }); 14 </script>