Android开源库之使用ZXing开源库二维码-实现竖屏且高识别率

ZXing开源库默认是横屏显示,在改为竖屏显示后,手动设定扫描匡的宽高,会发现近距离扫描二维码时,无法扫描成功,需要稍微远一点距离扫描,才能顺利扫描成功,分析应该是设置扫描匡的宽高后,其实际的扫描区域计算有问题,第1~4条借鉴博客,基本解决该问题,也感谢原博主,但是还稍微有点问题,就是在扫描复杂二维码时,识别率太低,这个问题在第5条中已经给出解决方法;

步骤:

1)   在AndroidManifest.xml中把  <Activity  />标签  CaptureActivity 的screenOrientation修改为

android:screenOrientation="portrait" 


2)  在CameraManager.java类中的getFramingRectInPreview()替换掉原先的 left right top bottom

//竖屏  
rect.left = rect.left * cameraResolution.y / screenResolution.x;   
rect.right = rect.right * cameraResolution.y / screenResolution.x;   
rect.top = rect.top * cameraResolution.x / screenResolution.y;   
rect.bottom = rect.bottom * cameraResolution.x / screenResolution.y;   

3)  在CameraConfigurationManager.java中void setDesiredCameraParameters(Camera camera)方法

在setParameters之前增加

camera.setDisplayOrientation(90);  

  co

4)  在DecodeHandler.java中的 decode(byte[] data, int width, int height)方法在

PlanarYUVLuminanceSource source = CameraManager.get().buildLuminanceSource(data, width, height);

之前添加:

byte[] rotatedData = new byte[data.length];   
 for (int y = 0; y < height; y++) {   
 for (int x = 0; x < width; x++)   
 rotatedData[x * height + height - y - 1] = data[x + y * width];   
 }   
 int tmp = width; // Here we are swapping, that's the difference to #11   
 width = height;   
 height = tmp;   
 data = rotatedData;  


5)上面几步基本已经搞定了横屏转竖屏需要远距离扫面的问题,扫面一般的二维码已经非常快,识别率很好,但是在扫描复杂二维码时,发现识别率非常低,有时很久识别不了,但是用原来的ZXing Demo扫描,虽然识别速度也要慢些,但是影响不大,识别率还是很高的,这就让人纳闷了;花时间好好看了下源码,并调试了n多次,终于发现问题了;ZXing Demo中camera选择的分辨率是1920 * 1080,但是我修改后的camera分辨率只有640 * 480,以至于真正扫描的图片分辨率过低,在扫描复杂二维码时,分辨率低的已经分不清文理,怎么可能识别出来啊!修改方法:
修改CameraConfigurationUtils类下的方法findBestPreviewSizeValue下的
double screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;
这段代码为:
 
 
double screenAspectRatio;
if(screenResolution.x > screenResolution.y){
  screenAspectRatio = (double) screenResolution.x / (double) screenResolution.y;
}else{
  screenAspectRatio = (double) screenResolution.y / (double) screenResolution.x;
}
这样无论是横屏还是竖屏,都能 正确找到最匹配的最大清晰度,识别率大大提高;
 
 






猜你喜欢

转载自blog.csdn.net/super_spy/article/details/52491758
今日推荐