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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值