一聚教程网:一个值得你收藏的教程网站

热门教程

Android Zxing 转换竖屏扫描且提高识别率的方法

时间:2022-06-25 22:57:46 编辑:袖梨 来源:一聚教程网

最近的一个Android需要用到扫码功能,用的是Zxing开源库。Zxing的集成就不说了,但是Zxing默认的是横屏扫码,在实际生产中并不适用,需要改为竖屏扫描。

转竖屏步骤:

1>. AndroidManifest.xml中把activity标签CaptureActivity部分的screenOrientation改为portrait。

android:screenOrientation="portrait"

2>. CameraManager类中的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类中的setDesiredCameraParameters(OpenCamera camera, boolean safeMode)方法,在setParameters之前添加

theCamera.setDisplayOrientation(90);

4>. DecodeHandler类中的decode(byte[] data, int width, int height)方法,在PlanarYUVLuminanceSource source = activity.getCameraManager().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;

此时,竖屏扫描已经可以实现了,但是扫描复杂的图码时,分辨率低的已经分不清纹理了,很难识别出来,所以需要优化识别率。

识别率优化:

1>. CameraConfigurationUtils类中的findBestPreviewSizeValue(Camera.Parameters parameters, Point screenResolution)方法,将double screenAspectRatio = 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;
}
2>. 至此,识别率已经很大程度上的提高了,若在要提高识别率,可通过修改CameraManager类中的MAX_FRAME_WIDTH和MAX_FRAME_HEIGHT来提高精度。

热门栏目