java生成二维码以及读取案例
今天有时间把二维码这块看了一下,方法有几种,我只是简单的看了一下 google 的 zxing!
很简单的一个,比较适合刚刚学习java的小伙伴哦!也比较适合以前没有接触过和感兴趣的的小伙伴,o(* ̄︶ ̄*)o
生成二维码 ,将二维码返回页面展示 ,读取二维码 !
首先添加需要的pom文件
<!-- https://mvnrepository.com/artifact/com.google.zxing/core --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.zxing/javase --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> </dependency>
想写点啥感觉好像也没啥写的o(* ̄︶ ̄*)o不多说 上代码
@RequestMapping("/test3")
public String test03(HttpServletRequest req){
System.out.println(1234);
final int width = 300;
final int height = 300;
final String format = "png";
final String content = "我爱你,中国!!!";
//定义二维码的参数
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
//生成二维码
try{
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
Path file = new File(req.getSession().getServletContext().getRealPath("")+"static\\img.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
}catch(Exception e){
}
return "index2";
}
这是在一个正常的项目里写的案例,随意的一个测试请求,返回了一个测试页面,就是获取项目的根路径,然后将生成的二维码保存在项目里面了,正常的话应该有单独的图片服务器吧!
页面案例代码,就是将图片回显出来了,很随意的一个案例
<div align="center" style="width: 100%;">
<img src="../static/img.png">
</div>
<div align="center" style="width: 100%;">
<button onclick="get();">getText</button>
</div>
<script type="text/javascript" src="../static/jquery.min.js"></script>
<script type="text/javascript">
function get() {
var url = "test4";
$.get(url,function(data){
alert(data.text);
});
}
</script>
效果如图

接下来就是获取二维码信息的案例了,为了简单,我直接在该页面添加了一个点击获取事件
下面是获取二维码的代码
@RequestMapping("/test4")
@ResponseBody
public Map test04(HttpServletRequest req) throws Exception {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File(req.getSession().getServletContext().getRealPath("")+"static\\img.png");
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//定义二维码的参数
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
System.out.println("二维码解析结果:" + result.toString());
System.out.println("二维码的格式:" + result.getBarcodeFormat());
System.out.println("二维码的文本内容:" + result.getText());
Map map = new HashMap();
map.put("text",result.getText());
return map;
}
就是发送了一个ajax请求,将二维码信息返回。然后弹出了一下
效果如图


浙公网安备 33010602011771号