在使用zxing开源库的时候,发现比较大的图片无法扫描成功,报如下异常:
com.google.zxing.NotFoundException
通过scale down Bitmap可以解决上述问题,720是一个Magic number,可以根据自己的项目调整
// Scale down the bitmap if it is bigger than we need.
int width = bm.getWidth();
int height = bm.getHeight();
final int targetWidth = 720, targetHeight = 720;
if (width > targetWidth || height > targetHeight) {
float scale = 0.0f;
if (width >= height) {
scale = (float) targetWidth / width;
} else {
scale = (float) targetHeight / height;
}
int w = Math.round(scale * width);
int h = Math.round(scale * height);
bm = Bitmap.createScaledBitmap(bm, w, h, true);
}
...
new QRCodeScanTask(picturePath).execute();
...
private class QRCodeScanTask extends AsyncTask<Void, Void, Result> {
private String imagePath;
private ProgressDialog mProgressDialog;
public QRCodeScanTask(String imagePath) {
this.imagePath = imagePath;
}
@Override
public void onPreExecute() {
mProgressDialog = new ProgressDialog(mActivity);
mProgressDialog.setMessage(mActivity.getString(R.string.qrcode_scanning));
mProgressDialog.show();
}
public Result doInBackground(Void... params) {
try{
MultiFormatReader multiFormatReader = new MultiFormatReader();
Bitmap bm = BitmapFactory.decodeFile(imagePath);
// Scale down the bitmap if it is bigger than we need.
int width = bm.getWidth();
int height = bm.getHeight();
final int targetWidth = 720, targetHeight = 720;
if (width > targetWidth || height > targetHeight) {
float scale = 0.0f;
if (width >= height) {
scale = (float) targetWidth / width;
} else {
scale = (float) targetHeight / height;
}
int w = Math.round(scale * width);
int h = Math.round(scale * height);
bm = Bitmap.createScaledBitmap(bm, w, h, true);
}
Result result = multiFormatReader.decodeWithState(new BinaryBitmap(
new HybridBinarizer(new BitmapLuminanceSource(bm))));
return result;
} catch(Exception e) {
return null;
}
}
@Override
public void onPostExecute(Result result){
mProgressDialog.dismiss();
if(result == null)
Toast.makeText(mActivity, R.string.qrcode_notfound, Toast.LENGTH_SHORT).show();
else
handleQRCodeResult(result);
}
}
PS:
1. 这里有相关的讨论 https://code.google.com/p/zxing/issues/detail?id=513
2. zxing github link: https://github.com/zxing/zxing/
来源:oschina
链接:https://my.oschina.net/u/172402/blog/386590