今天有時間把二維碼這塊看了一下,方法有幾種,我只是簡單的看了一下 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請求,將二維碼信息返回。然后彈出了一下
效果如圖

