[原创] Android 长按识别图中二维码 - Zxing

前提:
本文使用了 ButterKnife 依赖库
开始环境: Android Studio
在 Module 文件夹下的 build.gradle 文件中追加 zxing 依赖:

1
compile 'com.google.zxing:core:3.3.0'

之后添加图片长按事件(此处使用了 ButterKnife 的注解),并实现识别二维码的功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@OnLongClick({R.id.imageView})
public boolean btnLongClick(final ImageView iv) {
Logger.info(TAG, "Long click on image");
new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.recognize_qr_code, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
progressBar.setVisibility(View.VISIBLE);
Bitmap obmp = ((BitmapDrawable) (iv.getDrawable())).getBitmap();
int width = obmp.getWidth();
int height = obmp.getHeight();
int[] data = new int[width * height];
obmp.getPixels(data, 0, width, 0, 0, width, height);
RGBLuminanceSource source = new RGBLuminanceSource(width, height, data);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
new QrCodeAsyncTask().execute(bitmap);
}
}).show();
return true;
}
class QrCodeAsyncTask extends AsyncTask<BinaryBitmap, Void, Result> {
@Override
protected Result doInBackground(BinaryBitmap... params) {
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(params[0]);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(Result result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
String text = result.getText();
Logger.info(TAG, "QR CODE: " + text);
Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
}
}

坚持原创及高品质技术分享,您的支持将鼓励我继续创作!