java - 使用 ZXing 从图像(而不是相机)扫描二维码
问题描述
我正在使用 ZXing 库进行条码扫描。
我想使用这个库从图像(例如,在 SD 卡上)而不是从相机扫描条形码。
如何使用 ZXing 库做到这一点?
解决方案
我想在发布之前对其进行测试,所以花了我一段时间,我现在也在使用 ZXing,所以这对我来说也很方便:
首先,当然,从图库中读取图像(这可以在您的活动中):
Intent pickIntent = new Intent(Intent.ACTION_PICK);
pickIntent.setDataAndType( android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
startActivityForResult(pickIntent, 111);
之后,只需获取活动结果上的图像 uri,ZXing 就会发挥作用:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
//the case is because you might be handling multiple request codes here
case 111:
if(data == null || data.getData()==null) {
Log.e("TAG", "The uri is null, probably the user cancelled the image selection process using the back button.");
return;
}
Uri uri = data.getData();
try
{
InputStream inputStream = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null)
{
Log.e("TAG", "uri is not a bitmap," + uri.toString());
return;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
try
{
Result result = reader.decode(bBitmap);
Toast.makeText(this, "The content of the QR image is: " + result.getText(), Toast.LENGTH_SHORT).show();
}
catch (NotFoundException e)
{
Log.e("TAG", "decode exception", e);
}
}
catch (FileNotFoundException e)
{
Log.e("TAG", "can not open file" + uri.toString(), e);
}
break;
}
}
我对此进行了测试,它有效,干杯。
推荐阅读
- typescript - ask-sdk V2 中 Request 类型的类型定义不完整
- angular - Angular Material - 带图像的 mat-optgroup
- javascript - 无法检索隐藏字段值
- php - 从服务器检索数据花费了太多时间
- javascript - 量角器,如何选择href内的链接
- node.js - 如何为 npm install 命令设置超时
- python - 意外删除python库
- angular - Angular ServiceWorker:缓存多个 HTTP 请求
- google-cloud-platform - 缺少 MessageReceiver 类
- powershell - 使用 $host.ui.PromptForCredential 时输入值存储在哪里?