《打造极致二维码扫描系列》 -- ZBar开发详解

什么是ZBar?

ZBar是一个开源库,用于扫描、读取二维码和条形码。支持的二维码包括:EAN/UPC,QR等。


如果你是一个iPhone应用开发人员,做到二维码模块的时候,是不是会考虑ZBar开源项目来助你一臂之力呢?可是我这里说的是Android平台的开发,我为什么提到ZBar项目呢,难道我要用ZBar在Android平台扫描二维码吗?对的,没有错!这将会是一个极其不错的选择。为什么这么说呢,不是很多Android开发都是用ZXing来解析二维码的么?好吧,ZXing是我下一篇文章要写的,这里先抛砖引玉说一点点。我将ZXing和ZBar做一个比较,说说它们的优缺点,便于大家的取舍。



  • ZXing项目的示例程序对于摄像头的控制写的非常全面,ZBar的没有
  • ZBar基于C语言编写,解码效率高于ZXing项目
  • ZBar是日本人写的,对于中文解析会乱码这个肯定有人遇到过的,ZXing不会乱码
  • 扫描框的绘制,ZXing的扫描框绘制是自定义View的,截取区域不好控制(至少我没控制好),ZBar的可以自定义,只要你会计算截取区域


这里需要着重说一下第四点,我也是沿着解决这个第四点和第二点的问题才思考了这么多东西的。好烦躁自己的这种强迫症啊


下载ZBar项目

  • ZBar官网: http://zbar.sourceforge.net/
  • ZBar GitHub地址: https://github.com/ZBar/ZBar

编写ZBar示例程序

1. 着重介绍一下扫描截取界面的计算:




  • pt: 预览图中二维码图片的左上顶点坐标,也就是手机中相机预览中看到的待扫描二维码的位置
  • qrheight: 预览图中二维码图片的高度
  • qrwidth: 预览图中二维码图片的宽度
  • pheight:预览图的高度,也即camera的分辨率高度
  • pwidth: 预览图的宽度,也即camera的分辨率宽度



  • st: 布局文件中扫描框的左上顶点坐标
  • sheight: 布局文件中扫描框的高度
  • swidth: 布局文件中扫描框的宽度
  • cheight:布局文件中相机预览控件的高度
  • cwidth: 布局文件中相机预览控件的宽度


其中存在这样一个等比例公式:


ptx / pwidth = stx / cwidth ;

pty / pheight = stx / cheight ;

qrwidth / pwidth = swidth / cwidth ;

qrheight / pheight = sheight / cheight ;



即:


ptx = stx * pwidth / cwidth ;

pty = sty * pheight / cheight ;

qrwidth = swidth * pwidth / cwidth ;

qrheight = sheight * pheight / cheight ;



以上ptx,pty,qrwidth,qrheight四个参数也就是ZBar中解码是需要crop时传入的四个参数,如此便知道了截取区域应该如何计算了。这样扫描的灵活性都大大增强了,坐等看好戏把!!



2. ZBar中文乱码的解决

ZBar扫描含有中文的二维码图片时,结果是乱码的,所以需要修改c文件重新编译打包so文件才行。


a. 需要修改的文件是zbar/qrcode/qrdextxt.c文件

  1. /*This is the encoding the standard says is the default.*/
  2.   latin1_cd=iconv_open("UTF-8","ISO8859-1");
复制代码

修改为

  1. /*This is the encoding the standard says is the default.*/
  2.   latin1_cd=iconv_open("UTF-8","GBK");
复制代码

b. 重新编译zbar生成so文件

这个真的需要一定的NDK开发经验了,我个人只是了解一点点NDK的知识,所以在网上找到了一个大神的博客一步一步做下来才算是编译完成了。


其中NDK开发环境搭建可以参考: http://www.eoeandroid.com/forum.php?mod=viewthread&tid=272919

ZBar项目编译可以参考: http://www.blackdogfoundry.com/blog/zbar-bar-code-qr-code-reader-android/


最后的编译项目架构:



最终生成的so文件:



本地方法调用:

  1. package com.dtr.zbar.build;

  2. public class ZBarDecoder {

  3.         static {
  4.                 System.loadLibrary("ZBarDecoder");
  5.         }

  6.         /**
  7.          * 解码方法
  8.          * 
  9.          * @param data
  10.          *            图片数据
  11.          * @param width
  12.          *            原始宽度
  13.          * @param height
  14.          *            原始高度
  15.          * @return
  16.          */
  17.         public native String decodeRaw(byte[] data, int width, int height);

  18.         /**
  19.          * 解码方法(需要裁剪图片)
  20.          * 
  21.          * @param data
  22.          *            图片数据
  23.          * @param width
  24.          *            原始宽度
  25.          * @param height
  26.          *            原始高度
  27.          * @param x
  28.          *            截取的x坐标
  29.          * @param y
  30.          *            截取的y坐标
  31.          * @param cwidth
  32.          *            截取的区域宽度
  33.          * @param cheight
  34.          *            截取的区域高度
  35.          * @return
  36.          */
  37.         public native String decodeCrop(byte[] data, int width, int height, int x, int y, int cwidth, int cheight);
  38. }
复制代码

我的ZBar编译源程序代码:



3. 编写Android示例程序 a.安卓工程结构


其中CameraConfigurationManager和CameraManager两个类是从ZXing项目中拷贝过来的,方便管理照相机,下一篇的ZXing项目中会更全面的使用ZXing中关于camera的管理类,本篇只是抛砖迎玉。


b.布局界面代码

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:orientation="vertical" >

  6.     <RelativeLayout
  7.         android:id="@+id/capture_container"
  8.         android:layout_width="match_parent"
  9.         android:layout_height="match_parent" >

  10.         <FrameLayout
  11.             android:id="@+id/capture_preview"
  12.             android:layout_width="match_parent"
  13.             android:layout_height="match_parent" />

  14.         <ImageView
  15.             android:id="@+id/capture_mask_top"
  16.             android:layout_width="match_parent"
  17.             android:layout_height="120dp"
  18.             android:layout_alignParentTop="true"
  19.             android:background="@drawable/shadow" />

  20.         <RelativeLayout
  21.             android:id="@+id/capture_crop_view"
  22.             android:layout_width="200dp"
  23.             android:layout_height="200dp"
  24.             android:layout_centerHorizontal="true"
  25.             android:layout_below="@id/capture_mask_top"
  26.             android:background="@drawable/qr_code_bg" >

  27.             <ImageView
  28.                 android:id="@+id/capture_scan_line"
  29.                 android:layout_width="match_parent"
  30.                 android:layout_height="wrap_content"
  31.                 android:layout_alignParentTop="true"
  32.                 android:layout_marginBottom="5dp"
  33.                 android:layout_marginTop="5dp"
  34.                 android:src="@drawable/scan_line" />
  35.         </RelativeLayout>

  36.         <ImageView
  37.             android:id="@+id/capture_mask_bottom"
  38.             android:layout_width="match_parent"
  39.             android:layout_height="wrap_content"
  40.             android:layout_alignParentBottom="true"
  41.             android:layout_below="@id/capture_crop_view"
  42.             android:background="@drawable/shadow" />

  43.         <ImageView
  44.             android:id="@+id/capture_mask_left"
  45.             android:layout_width="wrap_content"
  46.             android:layout_height="match_parent"
  47.             android:layout_above="@id/capture_mask_bottom"
  48.             android:layout_alignParentLeft="true"
  49.             android:layout_below="@id/capture_mask_top"
  50.             android:layout_toLeftOf="@id/capture_crop_view"
  51.             android:background="@drawable/shadow" />

  52.         <ImageView
  53.             android:id="@+id/capture_mask_right"
  54.             android:layout_width="wrap_content"
  55.             android:layout_height="match_parent"
  56.             android:layout_above="@id/capture_mask_bottom"
  57.             android:layout_alignParentRight="true"
  58.             android:layout_below="@id/capture_mask_top"
  59.             android:layout_toRightOf="@id/capture_crop_view"
  60.             android:background="@drawable/shadow" />
  61.     </RelativeLayout>

  62.     <Button
  63.         android:id="@+id/capture_restart_scan"
  64.         android:layout_width="match_parent"
  65.         android:layout_height="40dp"
  66.         android:layout_alignParentBottom="true"
  67.         android:background="#66ffcc00"
  68.         android:gravity="center"
  69.         android:text="restart scan"
  70.         android:textColor="@android:color/white"
  71.         android:textSize="14sp" />

  72.     <TextView
  73.         android:id="@+id/capture_scan_result"
  74.         android:layout_width="match_parent"
  75.         android:layout_height="wrap_content"
  76.         android:layout_above="@id/capture_restart_scan"
  77.         android:layout_marginBottom="10dp"
  78.         android:gravity="center"
  79.         android:text="Scanning..."
  80.         android:textColor="@android:color/white"
  81.         android:textSize="14sp" />

  82. </RelativeLayout>
复制代码


c.扫描Activity关键代码

  1. package com.dtr.zbar.scan;

  2. import java.io.IOException;
  3. import java.lang.reflect.Field;

  4. import android.app.Activity;
  5. import android.content.pm.ActivityInfo;
  6. import android.graphics.Rect;
  7. import android.hardware.Camera;
  8. import android.hardware.Camera.AutoFocusCallback;
  9. import android.hardware.Camera.PreviewCallback;
  10. import android.hardware.Camera.Size;
  11. import android.os.Bundle;
  12. import android.os.Handler;
  13. import android.text.TextUtils;
  14. import android.view.View;
  15. import android.view.View.OnClickListener;
  16. import android.view.animation.Animation;
  17. import android.view.animation.TranslateAnimation;
  18. import android.widget.Button;
  19. import android.widget.FrameLayout;
  20. import android.widget.ImageView;
  21. import android.widget.RelativeLayout;
  22. import android.widget.TextView;

  23. import com.dtr.zbar.build.ZBarDecoder;

  24. public class CaptureActivity extends Activity {

  25.         private Camera mCamera;
  26.         private CameraPreview mPreview;
  27.         private Handler autoFocusHandler;
  28.         private CameraManager mCameraManager;

  29.         private TextView scanResult;
  30.         private FrameLayout scanPreview;
  31.         private Button scanRestart;
  32.         private RelativeLayout scanContainer;
  33.         private RelativeLayout scanCropView;
  34.         private ImageView scanLine;

  35.         private Rect mCropRect = null;
  36.         private boolean barcodeScanned = false;
  37.         private boolean previewing = true;

  38.         public void onCreate(Bundle savedInstanceState) {
  39.                 super.onCreate(savedInstanceState);
  40.                 setContentView(R.layout.activity_capture);
  41.                 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  42.                 findViewById();
  43.                 addEvents();
  44.                 initViews();
  45.         }

  46.         private void findViewById() {
  47.                 scanPreview = (FrameLayout) findViewById(R.id.capture_preview);
  48.                 scanResult = (TextView) findViewById(R.id.capture_scan_result);
  49.                 scanRestart = (Button) findViewById(R.id.capture_restart_scan);
  50.                 scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
  51.                 scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
  52.                 scanLine = (ImageView) findViewById(R.id.capture_scan_line);
  53.         }

  54.         private void addEvents() {
  55.                 scanRestart.setOnClickListener(new OnClickListener() {
  56.                         public void onClick(View v) {
  57.                                 if (barcodeScanned) {
  58.                                         barcodeScanned = false;
  59.                                         scanResult.setText("Scanning...");
  60.                                         mCamera.setPreviewCallback(previewCb);
  61.                                         mCamera.startPreview();
  62.                                         previewing = true;
  63.                                         mCamera.autoFocus(autoFocusCB);
  64.                                 }
  65.                         }
  66.                 });
  67.         }

  68.         private void initViews() {
  69.                 autoFocusHandler = new Handler();
  70.                 mCameraManager = new CameraManager(this);
  71.                 try {
  72.                         mCameraManager.openDriver();
  73.                 } catch (IOException e) {
  74.                         e.printStackTrace();
  75.                 }

  76.                 mCamera = mCameraManager.getCamera();
  77.                 mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
  78.                 scanPreview.addView(mPreview);

  79.                 TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
  80.                                 0.85f);
  81.                 animation.setDuration(3000);
  82.                 animation.setRepeatCount(-1);
  83.                 animation.setRepeatMode(Animation.REVERSE);
  84.                 scanLine.startAnimation(animation);
  85.         }

  86.         public void onPause() {
  87.                 super.onPause();
  88.                 releaseCamera();
  89.         }

  90.         private void releaseCamera() {
  91.                 if (mCamera != null) {
  92.                         previewing = false;
  93.                         mCamera.setPreviewCallback(null);
  94.                         mCamera.release();
  95.                         mCamera = null;
  96.                 }
  97.         }

  98.         private Runnable doAutoFocus = new Runnable() {
  99.                 public void run() {
  100.                         if (previewing)
  101.                                 mCamera.autoFocus(autoFocusCB);
  102.                 }
  103.         };

  104.         PreviewCallback previewCb = new PreviewCallback() {
  105.                 public void onPreviewFrame(byte[] data, Camera camera) {
  106.                         Size size = camera.getParameters().getPreviewSize();

  107.                         // 这里需要将获取的data翻转一下,因为相机默认拿的的横屏的数据
  108.                         byte[] rotatedData = new byte[data.length];
  109.                         for (int y = 0; y < size.height; y++) {
  110.                                 for (int x = 0; x < size.width; x++)
  111.                                         rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width];
  112.                         }

  113.                         // 宽高也要调整
  114.                         int tmp = size.width;
  115.                         size.width = size.height;
  116.                         size.height = tmp;

  117.                         initCrop();
  118.                         ZBarDecoder zBarDecoder = new ZBarDecoder();
  119.                         String result = zBarDecoder.decodeCrop(rotatedData, size.width, size.height, mCropRect.left, mCropRect.top, mCropRect.width(), mCropRect.height());

  120.                         if (!TextUtils.isEmpty(result)) {
  121.                                 previewing = false;
  122.                                 mCamera.setPreviewCallback(null);
  123.                                 mCamera.stopPreview();

  124.                                 scanResult.setText("barcode result " + result);
  125.                                 barcodeScanned = true;
  126.                         }
  127.                 }
  128.         };

  129.         // Mimic continuous auto-focusing
  130.         AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
  131.                 public void onAutoFocus(boolean success, Camera camera) {
  132.                         autoFocusHandler.postDelayed(doAutoFocus, 1000);
  133.                 }
  134.         };

  135.         /**
  136.          * 初始化截取的矩形区域
  137.          */
  138.         private void initCrop() {
  139.                 int cameraWidth = mCameraManager.getCameraResolution().y;
  140.                 int cameraHeight = mCameraManager.getCameraResolution().x;

  141.                 /** 获取布局中扫描框的位置信息 */
  142.                 int[] location = new int[2];
  143.                 scanCropView.getLocationInWindow(location);

  144.                 int cropLeft = location[0];
  145.                 int cropTop = location[1] - getStatusBarHeight();

  146.                 int cropWidth = scanCropView.getWidth();
  147.                 int cropHeight = scanCropView.getHeight();

  148.                 /** 获取布局容器的宽高 */
  149.                 int containerWidth = scanContainer.getWidth();
  150.                 int containerHeight = scanContainer.getHeight();

  151.                 /** 计算最终截取的矩形的左上角顶点x坐标 */
  152.                 int x = cropLeft * cameraWidth / containerWidth;
  153.                 /** 计算最终截取的矩形的左上角顶点y坐标 */
  154.                 int y = cropTop * cameraHeight / containerHeight;

  155.                 /** 计算最终截取的矩形的宽度 */
  156.                 int width = cropWidth * cameraWidth / containerWidth;
  157.                 /** 计算最终截取的矩形的高度 */
  158.                 int height = cropHeight * cameraHeight / containerHeight;

  159.                 /** 生成最终的截取的矩形 */
  160.                 mCropRect = new Rect(x, y, width + x, height + y);
  161.         }

  162.         private int getStatusBarHeight() {
  163.                 try {
  164.                         Class<?> c = Class.forName("com.android.internal.R$dimen");
  165.                         Object obj = c.newInstance();
  166.                         Field field = c.getField("status_bar_height");
  167.                         int x = Integer.parseInt(field.get(obj).toString());
  168.                         return getResources().getDimensionPixelSize(x);
  169.                 } catch (Exception e) {
  170.                         e.printStackTrace();
  171.                 }
  172.                 return 0;
  173.         }
  174. }
复制代码


d.运行效果图





下一篇将介绍如何使用ZXing项目代码扫描二维码图片,亮点在于去掉ViewFinderView,使用xml布局界面

希望大家多多访问我的CSDN博客,将会第一时间发布新东西:   http://blog.csdn.net/skillcollege
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值