Java生成二維碼連結或解析二維碼
-
- 生成二維碼
-
- 1、引入二維碼插件
- 2、Controller 擷取生成二維碼連結
- 3、Service 接口
- 4、Service 接口實作類
- 5、Util 工具類
- 解析二維碼
1、開發微信小程式接入廣告擷取收益!!
生成二維碼
1、引入二維碼插件
<!-- 二維碼 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
2、Controller 擷取生成二維碼連結
@Api2Doc(order = 16)
@ApiComment("擷取邀請二維碼接口")
@RequestMapping(name = "擷取邀請二維碼接口", value = "/qrCode", method = RequestMethod.GET)
public String getQrCode(@ApiComment(value = "生成二維碼連接配接", sample = "http://127.0.0.1/[email protected]")
@RequestParam(value = "url") String url) {
String qrCode = "";
try {
qrCode = memberInfoService.getQrCode(url);
} catch (Exception e) {
logger.error("",e);
}
return qrCode;
}
3、Service 接口
4、Service 接口實作類
@Override
public String getQrCode(String url) {
String qrCode = "qrCode.jpg";//二維碼圖檔名稱
String imagePath = "E:/txdata/data/images/";//二維碼圖檔存放位址
String qrCodeUrl = “http://127.0.0.1:80/”;//請求路徑
ERCodeUtil.encodeQR(imagePath, "qrCode.jpg", "jpg", url, 300, 300);//生成二維碼方法
return qrCodeUrl + qrCode;//傳回二維碼連結位址
}
5、Util 工具類
/**
* 生成二維碼
*
* @param filePath 檔案儲存路徑
* @param fileName 檔案名稱
* @param format 圖檔格式
* @param content 二維碼包含内容
* @param width 寬度
* @param height 高度
*/
public static void encodeQR(String filePath, String fileName, String format, String content, int width, int height) {
try {
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 生成矩陣
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
Path path = FileSystems.getDefault().getPath(filePath, fileName);
// 輸出圖像
MatrixToImageWriter.writeToPath(bitMatrix, format, path);
} catch (Exception e) {
e.printStackTrace();
}
}
根據連結生成二維碼就完成了、如果要解析二維碼如下:
解析二維碼
/**
* 解析二維碼
*/
public static void decodeQR() {
String filePath = "E:/txdata/data/images/qrCode.jpg";//二維碼路徑
BufferedImage image;
try {
image = ImageIO.read(new File(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 對圖像進行解碼
logger.info("圖檔中内容: ");
logger.info("author: " + result.getText());
logger.info("圖檔中格式: ");
logger.info("encode: " + result.getBarcodeFormat());
} catch (IOException e) {
e.printStackTrace();
} catch (NotFoundException e) {
e.printStackTrace();
}
}
解析輸出内容:
圖檔中内容: http://localhost:8080/regest?cKey=@r0313184957
圖檔中格式: QR_CODE