基于google zxing的Java二維碼生成與解碼
更新時間:2017年07月26日 08:43:35 作者:二十六度半
這篇文章主要為大家詳細介紹了基于google zxing的Java二維碼生成與解碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Java二維碼生成與解碼的具體代碼,供大家參考,具體內容如下
一、添加Maven依賴(解碼時需要上傳二維碼圖片,所以需要依賴文件上傳包)
<!-- google二維碼工具 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.1.0</version> </dependency> <!-- 文件上傳 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
二、創(chuàng)建生成二維碼接口(接口參數為二維碼內容,通常是URL)
/**
* 生成二維碼
* google zxing 實現
* @param text
* @return
*/
@RequestMapping(value = "/qrcode/encode", method = RequestMethod.POST)
public void encodeQrCode(String text, HttpServletResponse response) {
try {
// 設置二維碼參數
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 150, 150, hints);
//返回二維碼
MatrixToImageWriter.writeToStream(bitMatrix, "jpg", response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
三、創(chuàng)建二維碼解碼接口(直接返回解碼后的二維碼內容)
/**
* 二維碼圖片解碼
* google zxing 實現
* @param qrImg
* @return
*/
@RequestMapping(value = "/qrcode/decode", method = RequestMethod.POST)
public String decodeQrCode(MultipartFile qrImg) {
if (!qrImg.isEmpty()) {
try {
BufferedImage image = ImageIO.read(qrImg.getInputStream());
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
// 定義二維碼的參數:
HashMap<DecodeHintType, Object> hints = new HashMap<>();
// 定義字符集
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
使用ByteArrayOutputStream寫入字符串方式
這篇文章主要介紹了使用ByteArrayOutputStream寫入字符串方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
Netty分布式pipeline管道Handler的刪除邏輯操作
這篇文章主要為大家介紹了Netty分布式pipeline管道Handler的刪除邏輯操作,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-03-03
redis setIfAbsent和setnx的區(qū)別與使用說明
這篇文章主要介紹了redis setIfAbsent和setnx的區(qū)別與使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08
Java并發(fā)系列之ReentrantLock源碼分析
這篇文章主要為大家詳細介紹了Java并發(fā)系列之ReentrantLock源碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
解析Springboot集成Tile38客戶端之Set命令實現示例
這篇文章主要為大家介紹了解析Springboot集成Tile38客戶端之Set命令實現示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08

