Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3053357
  • 博文数量: 396
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 4209
  • 用 户 组: 普通用户
  • 注册时间: 2016-07-04 13:04
文章分类

全部博文(396)

文章存档

2022年(1)

2021年(2)

2020年(8)

2019年(24)

2018年(135)

2017年(158)

2016年(68)

我的朋友

分类: 嵌入式

2017-12-21 13:47:58

什么是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官网:
  • ZBar GitHub地址:

编写ZBar示例程序


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

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

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


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


ptx / pwidth = stx / cwidth ;

pty / pheight = sty / 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开发环境搭建可以参考: 

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


最后的编译项目架构:


最终生成的so文件:

本地方法调用:

[java] view plain copy
  1. package com.dtr.zbar.build;  
  2.   
  3. public class ZBarDecoder {  
  4.   
  5.     static {  
  6.         System.loadLibrary("ZBarDecoder");  
  7.     }  
  8.   
  9.     /** 
  10.      * 解码方法 
  11.      *  
  12.      * @param data 
  13.      *            图片数据 
  14.      * @param width 
  15.      *            原始宽度 
  16.      * @param height 
  17.      *            原始高度 
  18.      * @return 
  19.      */  
  20.     public native String decodeRaw(byte[] data, int width, int height);  
  21.   
  22.     /** 
  23.      * 解码方法(需要裁剪图片) 
  24.      *  
  25.      * @param data 
  26.      *            图片数据 
  27.      * @param width 
  28.      *            原始宽度 
  29.      * @param height 
  30.      *            原始高度 
  31.      * @param x 
  32.      *            截取的x坐标 
  33.      * @param y 
  34.      *            截取的y坐标 
  35.      * @param cwidth 
  36.      *            截取的区域宽度 
  37.      * @param cheight 
  38.      *            截取的区域高度 
  39.      * @return 
  40.      */  
  41.     public native String decodeCrop(byte[] data, int width, int height, int x, int y, int cwidth, int cheight);  
  42. }  


我的ZBar编译源程序代码:


3. 编写Android示例程序

a.安卓工程结构

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


b.布局界面代码
[html] view plain copy
  1. xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android=""  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <RelativeLayout  
  8.         android:id="@+id/capture_container"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" >  
  11.   
  12.         <FrameLayout  
  13.             android:id="@+id/capture_preview"  
  14.             android:layout_width="match_parent"  
  15.             android:layout_height="match_parent" />  
  16.   
  17.         <ImageView  
  18.             android:id="@+id/capture_mask_top"  
  19.             android:layout_width="match_parent"  
  20.             android:layout_height="120dp"  
  21.             android:layout_alignParentTop="true"  
  22.             android:background="@drawable/shadow" />  
  23.   
  24.         <RelativeLayout  
  25.             android:id="@+id/capture_crop_view"  
  26.             android:layout_width="200dp"  
  27.             android:layout_height="200dp"  
  28.             android:layout_centerHorizontal="true"  
  29.             android:layout_below="@id/capture_mask_top"  
  30.             android:background="@drawable/qr_code_bg" >  
  31.   
  32.             <ImageView  
  33.                 android:id="@+id/capture_scan_line"  
  34.                 android:layout_width="match_parent"  
  35.                 android:layout_height="wrap_content"  
  36.                 android:layout_alignParentTop="true"  
  37.                 android:layout_marginBottom="5dp"  
  38.                 android:layout_marginTop="5dp"  
  39.                 android:src="@drawable/scan_line" />  
  40.         RelativeLayout>  
  41.   
  42.         <ImageView  
  43.             android:id="@+id/capture_mask_bottom"  
  44.             android:layout_width="match_parent"  
  45.             android:layout_height="wrap_content"  
  46.             android:layout_alignParentBottom="true"  
  47.             android:layout_below="@id/capture_crop_view"  
  48.             android:background="@drawable/shadow" />  
  49.   
  50.         <ImageView  
  51.             android:id="@+id/capture_mask_left"  
  52.             android:layout_width="wrap_content"  
  53.             android:layout_height="match_parent"  
  54.             android:layout_above="@id/capture_mask_bottom"  
  55.             android:layout_alignParentLeft="true"  
  56.             android:layout_below="@id/capture_mask_top"  
  57.             android:layout_toLeftOf="@id/capture_crop_view"  
  58.             android:background="@drawable/shadow" />  
  59.   
  60.         <ImageView  
  61.             android:id="@+id/capture_mask_right"  
  62.             android:layout_width="wrap_content"  
  63.             android:layout_height="match_parent"  
  64.             android:layout_above="@id/capture_mask_bottom"  
  65.             android:layout_alignParentRight="true"  
  66.             android:layout_below="@id/capture_mask_top"  
  67.             android:layout_toRightOf="@id/capture_crop_view"  
  68.             android:background="@drawable/shadow" />  
  69.     RelativeLayout>  
  70.   
  71.     <Button  
  72.         android:id="@+id/capture_restart_scan"  
  73.         android:layout_width="match_parent"  
  74.         android:layout_height="40dp"  
  75.         android:layout_alignParentBottom="true"  
  76.         android:background="#66ffcc00"  
  77.         android:gravity="center"  
  78.         android:text="restart scan"  
  79.         android:textColor="@android:color/white"  
  80.         android:textSize="14sp" />  
  81.   
  82.     <TextView  
  83.         android:id="@+id/capture_scan_result"  
  84.         android:layout_width="match_parent"  
  85.         android:layout_height="wrap_content"  
  86.         android:layout_above="@id/capture_restart_scan"  
  87.         android:layout_marginBottom="10dp"  
  88.         android:gravity="center"  
  89.         android:text="Scanning..."  
  90.         android:textColor="@android:color/white"  
  91.         android:textSize="14sp" />  
  92.   
  93. RelativeLayout>  

c.扫描Activity关键代码
[java] view plain copy
  1. package com.dtr.zbar.scan;  
  2.   
  3. import java.io.IOException;  
  4. import java.lang.reflect.Field;  
  5.   
  6. import android.app.Activity;  
  7. import android.content.pm.ActivityInfo;  
  8. import android.graphics.Rect;  
  9. import android.hardware.Camera;  
  10. import android.hardware.Camera.AutoFocusCallback;  
  11. import android.hardware.Camera.PreviewCallback;  
  12. import android.hardware.Camera.Size;  
  13. import android.os.Bundle;  
  14. import android.os.Handler;  
  15. import android.text.TextUtils;  
  16. import android.view.View;  
  17. import android.view.View.OnClickListener;  
  18. import android.view.animation.Animation;  
  19. import android.view.animation.TranslateAnimation;  
  20. import android.widget.Button;  
  21. import android.widget.FrameLayout;  
  22. import android.widget.ImageView;  
  23. import android.widget.RelativeLayout;  
  24. import android.widget.TextView;  
  25.   
  26. import com.dtr.zbar.build.ZBarDecoder;  
  27.   
  28. public class CaptureActivity extends Activity {  
  29.   
  30.     private Camera mCamera;  
  31.     private CameraPreview mPreview;  
  32.     private Handler autoFocusHandler;  
  33.     private CameraManager mCameraManager;  
  34.   
  35.     private TextView scanResult;  
  36.     private FrameLayout scanPreview;  
  37.     private Button scanRestart;  
  38.     private RelativeLayout scanContainer;  
  39.     private RelativeLayout scanCropView;  
  40.     private ImageView scanLine;  
  41.   
  42.     private Rect mCropRect = null;  
  43.     private boolean barcodeScanned = false;  
  44.     private boolean previewing = true;  
  45.   
  46.     public void onCreate(Bundle savedInstanceState) {  
  47.         super.onCreate(savedInstanceState);  
  48.         setContentView(R.layout.activity_capture);  
  49.         setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);  
  50.         findViewById();  
  51.         addEvents();  
  52.         initViews();  
  53.     }  
  54.   
  55.     private void findViewById() {  
  56.         scanPreview = (FrameLayout) findViewById(R.id.capture_preview);  
  57.         scanResult = (TextView) findViewById(R.id.capture_scan_result);  
  58.         scanRestart = (Button) findViewById(R.id.capture_restart_scan);  
  59.         scanContainer = (RelativeLayout) findViewById(R.id.capture_container);  
  60.         scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);  
  61.         scanLine = (ImageView) findViewById(R.id.capture_scan_line);  
  62.     }  
  63.   
  64.     private void addEvents() {  
  65.         scanRestart.setOnClickListener(new OnClickListener() {  
  66.             public void onClick(View v) {  
  67.                 if (barcodeScanned) {  
  68.                     barcodeScanned = false;  
  69.                     scanResult.setText("Scanning...");  
  70.                     mCamera.setPreviewCallback(previewCb);  
  71.                     mCamera.startPreview();  
  72.                     previewing = true;  
  73.                     mCamera.autoFocus(autoFocusCB);  
  74.                 }  
  75.             }  
  76.         });  
  77.     }  
  78.   
  79.     private void initViews() {  
  80.         autoFocusHandler = new Handler();  
  81.         mCameraManager = new CameraManager(this);  
  82.         try {  
  83.             mCameraManager.openDriver();  
  84.         } catch (IOException e) {  
  85.             e.printStackTrace();  
  86.         }  
  87.   
  88.         mCamera = mCameraManager.getCamera();  
  89.         mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);  
  90.         scanPreview.addView(mPreview);  
  91.   
  92.         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,  
  93.                 0.85f);  
  94.         animation.setDuration(3000);  
  95.         animation.setRepeatCount(-1);  
  96.         animation.setRepeatMode(Animation.REVERSE);  
  97.         scanLine.startAnimation(animation);  
  98.     }  
  99.   
  100.     public void onPause() {  
  101.         super.onPause();  
  102.         releaseCamera();  
  103.     }  
  104.   
  105.     private void releaseCamera() {  
  106.         if (mCamera != null) {  
  107.             previewing = false;  
  108.             mCamera.setPreviewCallback(null);  
  109.             mCamera.release();  
  110.             mCamera = null;  
  111.         }  
  112.     }  
  113.   
  114.     private Runnable doAutoFocus = new Runnable() {  
  115.         public void run() {  
  116.             if (previewing)  
  117.                 mCamera.autoFocus(autoFocusCB);  
  118.         }  
  119.     };  
  120.   
  121.     PreviewCallback previewCb = new PreviewCallback() {  
  122.         public void onPreviewFrame(byte[] data, Camera camera) {  
  123.             Size size = camera.getParameters().getPreviewSize();  
  124.   
  125.             // 这里需要将获取的data翻转一下,因为相机默认拿的的横屏的数据  
  126.             byte[] rotatedData = new byte[data.length];  
  127.             for (int y = 0; y < size.height; y++) {  
  128.                 for (int x = 0; x < size.width; x++)  
  129.                     rotatedData[x * size.height + size.height - y - 1] = data[x + y * size.width];  
  130.             }  
  131.   
  132.             // 宽高也要调整  
  133.             int tmp = size.width;  
  134.             size.width = size.height;  
  135.             size.height = tmp;  
  136.   
  137.             initCrop();  
  138.             ZBarDecoder zBarDecoder = new ZBarDecoder();  
  139.             String result = zBarDecoder.decodeCrop(rotatedData, size.width, size.height, mCropRect.left, mCropRect.top, mCropRect.width(), mCropRect.height());  
  140.   
  141.             if (!TextUtils.isEmpty(result)) {  
  142.                 previewing = false;  
  143.                 mCamera.setPreviewCallback(null);  
  144.                 mCamera.stopPreview();  
  145.   
  146.                 scanResult.setText("barcode result " + result);  
  147.                 barcodeScanned = true;  
  148.             }  
  149.         }  
  150.     };  
  151.   
  152.     // Mimic continuous auto-focusing  
  153.     AutoFocusCallback autoFocusCB = new AutoFocusCallback() {  
  154.         public void onAutoFocus(boolean success, Camera camera) {  
  155.             autoFocusHandler.postDelayed(doAutoFocus, 1000);  
  156.         }  
  157.     };  
  158.   
  159.     /** 
  160.      * 初始化截取的矩形区域 
  161.      */  
  162.     private void initCrop() {  
  163.         int cameraWidth = mCameraManager.getCameraResolution().y;  
  164.         int cameraHeight = mCameraManager.getCameraResolution().x;  
  165.   
  166.         /** 获取布局中扫描框的位置信息 */  
  167.         int[] location = new int[2];  
  168.         scanCropView.getLocationInWindow(location);  
  169.   
  170.         int cropLeft = location[0];  
  171.         int cropTop = location[1] - getStatusBarHeight();  
  172.   
  173.         int cropWidth = scanCropView.getWidth();  
  174.         int cropHeight = scanCropView.getHeight();  
  175.   
  176.         /** 获取布局容器的宽高 */  
  177.         int containerWidth = scanContainer.getWidth();  
  178.         int containerHeight = scanContainer.getHeight();  
  179.   
  180.         /** 计算最终截取的矩形的左上角顶点x坐标 */  
  181.         int x = cropLeft * cameraWidth / containerWidth;  
  182.         /** 计算最终截取的矩形的左上角顶点y坐标 */  
  183.         int y = cropTop * cameraHeight / containerHeight;  
  184.   
  185.         /** 计算最终截取的矩形的宽度 */  
  186.         int width = cropWidth * cameraWidth / containerWidth;  
  187.         /** 计算最终截取的矩形的高度 */  
  188.         int height = cropHeight * cameraHeight / containerHeight;  
  189.   
  190.         /** 生成最终的截取的矩形 */  
  191.         mCropRect = new Rect(x, y, width + x, height + y);  
  192.     }  
  193.   
  194.     private int getStatusBarHeight() {  
  195.         try {  
  196.             Class c = Class.forName("com.android.internal.R$dimen");  
  197.             Object obj = c.newInstance();  
  198.             Field field = c.getField("status_bar_height");  
  199.             int x = Integer.parseInt(field.get(obj).toString());  
  200.             return getResources().getDimensionPixelSize(x);  
  201.         } catch (Exception e) {  
  202.             e.printStackTrace();  
  203.         }  
  204.         return 0;  
  205.     }  
  206. }  
d.运行效果图



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



阅读(2795) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~