Android ZXing识别图片中的一维码和二维码的简单总结

一、前言

     我在网上找了很多关于识别一维码和二维码的资料,总结一下,手机端目前能找到ZXing,ZBar都只能支持单个一维码,单个和多个二维码的识别,当图片有二维码和一维码同时存在,也只能识别二维码,而且ZXing还在持续更新中,所以最好的选择是ZXing。

二、代码和使用

/**
* 扫描的工具类-------一维码二维码(识别图片)
* **/
public class BarcodeUtil {

/***
* 获取图片的一维码----目前只支持一个条形码 filename --图片的绝对路径
* */
public static String getOneBarcode(String filename, Context context) {
String onebarcode = "";

Bitmap img = BitmapUtils.getCompressedBitmap(filename);
BitmapDecoder decoder = new BitmapDecoder(context);
Result result = decoder.getRawResult(img);
String resP = "";
if (result != null
&& codeType(DecodeFormatManager.ONE_D_FORMATS,
result.getBarcodeFormat())) {
resP = "|" + result.getResultPoints()[1].getX() + "|"
+ result.getResultPoints()[1].getY() + "|";
onebarcode = result.getText() + resP;
}
return onebarcode;

}

/***
* 获取图片的二维码----目前可支持多个二维码 filename --图片的绝对路径
* */
public static String getTwoBarcode(String filename) {
String twobarcode = "";
Bitmap img = BitmapUtils.getCompressedBitmap(filename);
int[] intArray = new int[img.getWidth() * img.getHeight()];
img.getPixels(intArray, 0, img.getWidth(), 0, 0, img.getWidth(),
img.getHeight());

LuminanceSource source = new RGBLuminanceSource(img.getWidth(),
img.getHeight(), intArray);

BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

QRCodeMultiReader odecoder = new QRCodeMultiReader();
Result[] results;
String resP = "";
try {
results = odecoder.decodeMultiple(bitmap);
if (results != null) {
for (Result result2 : results) {
if (result2 != null
&& codeType(DecodeFormatManager.QR_CODE_FORMATS,
result2.getBarcodeFormat())) {
resP = "|" + result2.getResultPoints()[1].getX() + "|"
+ result2.getResultPoints()[1].getY() + "|";
twobarcode += result2.getText() + resP;
}
}
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return twobarcode;

}

/***
* 确认扫描的
*
* */
private static boolean codeType(final Collection<BarcodeFormat> type,
BarcodeFormat barcodeFormat) {
for (BarcodeFormat barcode : type) {
if (barcodeFormat.equals(barcode)) {
return true;
}
}
return false;
}

}

说明 :我这个同时返回了一维码或二维码包含的信息还有它所在位置的左上角的那个坐标点。

(result.getResultPoints()[1].getX() +result.getResultPoints()[1].getY() 这是左上角那个点的坐标) 一维码只返回两个坐标,二维码返回了4个,根据你的需要去取。

重点说明:对多个二维码的识别,需要使用QRCodeMultiReader去识别,很多地方找不到这个类的具体使用方法,你需要下载一个比较新版本的ZXing包,里面才有这方法。

其他相关的一些工具类,你也可以在对应的里面找到。因为关于ZXing的使用很容易在GitHub等地方找到demo,但是对多个扫描的二维码的识别就基本没有使用的例子,使用的方法都提供了,但没有直接的使用总结,所以我这里贴的就是我的一个简单的使用和说明,希望可以帮到你。



转载于:https://juejin.im/post/5a5709096fb9a01caa2071d4

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值