ZXing解析二维码,条码
前言
要解析二维码或者条形码,首先要保证这个文件是正常无损坏能正常识别的,这里有时会有一个问题,手机扫码可以识别,但是代码解析码时会报错,这个时候需要自己先测试一下
这里给一个网址用作解析二维码,这里面能解析出来就排除文件问题,网址
这种就是解析失败的
一、ZXing解析二维码
ZXing解析普通二维码和logo二维码,这里有俩行代码需要解释一下
//精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
这俩行代码只能用作二维码(格式:QR_CODE)解析,其他的条码请注释
/**
* @param path 二维码路径
*/
public static void qrCode(String path){
BufferedImage image;
try {
image = ImageIO.read(new File(path));
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");
//精度
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
//复杂模式
hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码
System.out.println("图片: "+ result.toString());
System.out.println("图片中内容: "+ result.getText());
System.out.println("图片中格式: " + result.getBarcodeFormat());
} catch (Exception e) {
e.printStackTrace();
}
}
二、ZXing解析条码
/**
*条形码解码
*
* @param imgPath
* @return String
*/
public static String decode(String imgPath) {
BufferedImage image = null;
Result result = null;
try {
image = ImageIO.read(new File(imgPath));
if (image == null) {
System.out.println("获取图片失败");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = new MultiFormatReader().decode(bitmap, null);
return result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
测试
//解析条码
String imgPath = "D:/zxing_EAN-132.png";
String contents = "6926557300360";
int width = 400, height = 100;
//生成条码
encode(contents, width, height, imgPath);
//解析条码
String decodeContent = decode(imgPath);
System.out.println("解码内容如下:" + decodeContent);
//解析二维码或带logo的二维码
String path = "D:/qr.png";
qrCode(path);
结果
CODE_128
解码内容如下:6926557300360
图片: https://www.baidu.com/
图片中内容: https://www.baidu.com/
图片中格式: QR_CODE