java读取网络二微码图片并获取二微码信息
pom.xml中添加依赖:
<!-- 解码二微码图片 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.0.0</version>
</dependency>
解码方法:
/**
* 读取网上的二微码图片并解析,最后将二微码实际内容返回
* @param imageUrl 二微码图片地址
*/
public static String decodeQrcode(String imageUrl) {
try {
//new一个URL对象
URL url =new URL(imageUrl);
//打开链接
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置请求方式为"GET"
conn.setRequestMethod("GET");
//超时响应时间为5秒
conn.setConnectTimeout(5 *1000);
//通过输入流获取图片数据
InputStream inStream =conn.getInputStream();
BufferedImage bufferedImage =ImageIO.read(inStream);
LuminanceSource source =new BufferedImageLuminanceSource(bufferedImage);
Binarizer binarizer =new HybridBinarizer(source);
BinaryBitmap bitmap =new BinaryBitmap(binarizer);
HashMapdecodeHints =new HashMap();
decodeHints.put(DecodeHintType.PURE_BARCODE,Boolean.TRUE);
Result result =new MultiFormatReader().decode(bitmap,decodeHints);
return result.getText();
}catch (Exception e) {
logger.error("二微码图片解析失败:" +e.getMessage());
return null;
}
}