在Android上使用ZXing識別條形碼/二維碼
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow
也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!
本文來自http://blog.csdn.net/hellogv/ ,引用必須註明出處!
越來越多的手機具備自動對焦的拍攝功能,這也意味著這些手機可以具備條碼掃描的功能.......手機具備條碼掃描的功能,可以優化購物流程,快速儲存電子名片(二維碼)等
本文使用ZXing 1.6實現條碼/二維碼識別。ZXing是個很經典的條碼/二維碼識別的開源類庫,long long ago,就有開發者在J2ME上使用ZXing了,不過要支援JSR-234規範(自動對焦)的手機才能發揮其威力,而目前已經有不少Android手機具備自動對焦的功能。
本文程式碼執行的結果如下,使用91手機助手截圖時,無法擷取SurfaceView的實時影象:
本文使用了ZXing1.6的core,即把/zxing-1.6/core/下的src複製覆蓋工程的src;另外還要使用到/zxing-1.6/android/下的PlanarYUVLuminanceSource.java。
PS:/zxing-1.6/android/ 是BarcodeScanner的原始碼,本文程式相當於BarcodeScanner的精簡版,只保留最基本的識別功能。
本文原始碼工程的下載地址如下:http://www.pudn.com/downloads349/sourcecode/comm/android/detail1521939.html
原始碼目錄結果如下圖,ChecksumException.java下面還有很多原始檔,截圖尚未列出:
本文例子必須要開攝像頭和自動對焦的許可權,不然啟動時會報異常,所用的許可權如下:
<textarea cols="50" rows="15" name="code" class="xhtml"><uses-permission android:name="android.permission.CAMERA"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><uses-feature android:name="android.hardware.camera" /><uses-feature android:name="android.hardware.camera.autofocus" /></textarea>
main.xml原始碼如下,main.xml必須要用到FrameLayout才能重疊控制元件實現“範圍框”的效果:
[xhtml] view plain copy print ?
- <?xml version="1.0" encoding="utf-8"?>
- <FrameLayout android:id="@+id/FrameLayout01"
- android:layout_width="fill_parent" android:layout_height="fill_parent"
- xmlns:android="http://schemas.android.com/apk/res/android">
- <SurfaceView android:layout_height="fill_parent"
- android:id="@+id/sfvCamera" android:layout_width="fill_parent"></SurfaceView>
- <RelativeLayout android:id="@+id/RelativeLayout01"
- android:layout_height="fill_parent" android:layout_width="fill_parent">
- <ImageView android:id="@+id/ImageView01"
- android:layout_height="100dip" android:layout_width="160dip"></ImageView>
- <View android:layout_centerVertical="true"
- android:layout_centerHorizontal="true" android:layout_width="300dip"
- android:background="#55FF6666" android:id="@+id/centerView"
- android:layout_height="180dip"></View>
- <TextView android:layout_centerHorizontal="true"
- android:layout_width="wrap_content" android:layout_below="@+id/centerView"
- android:layout_height="wrap_content" android:text="Scanning..."
- android:id="@+id/txtScanResult" android:textColor="#FF000000"></TextView>
- </RelativeLayout>
- </FrameLayout>
testCamera.java是主類,負責控制Camera和對影象做解碼,原始碼如下:
<textarea cols="50" rows="15" name="code" class="java">package com.testCamera;import java.util.Timer;import java.util.TimerTask;import com.google.zxing.BinaryBitmap;import com.google.zxing.MultiFormatReader;import com.google.zxing.Result;import com.google.zxing.Android.PlanarYUVLuminanceSource;import com.google.zxing.common.HybridBinarizer;import android.app.Activity;import android.graphics.Bitmap;import android.hardware.Camera;import android.os.Bundle;import android.view.SurfaceView;import android.view.View;import android.widget.ImageView;import android.widget.TextView;public class testCamera extends Activity { /** Called when the activity is first created. */ private SurfaceView sfvCamera; private SFHCamera sfhCamera; private ImageView imgView; private View centerView; private TextView txtScanResult; private Timer mTimer; private MyTimerTask mTimerTask; // 按照標準HVGA final static int width = 480; final static int height = 320; int dstLeft, dstTop, dstWidth, dstHeight; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.setTitle("Android條碼/二維碼識別Demo-----hellogv"); imgView = (ImageView) this.findViewById(R.id.ImageView01); centerView = (View) this.findViewById(R.id.centerView); sfvCamera = (SurfaceView) this.findViewById(R.id.sfvCamera); sfhCamera = new SFHCamera(sfvCamera.getHolder(), width, height, previewCallback); txtScanResult=(TextView)this.findViewById(R.id.txtScanResult); // 初始化定時器 mTimer = new Timer(); mTimerTask = new MyTimerTask(); mTimer.schedule(mTimerTask, 0, 80); } class MyTimerTask extends TimerTask { @Override public void run() { if (dstLeft == 0) {//只賦值一次 dstLeft = centerView.getLeft() * width / getWindowManager().getDefaultDisplay().getWidth(); dstTop = centerView.getTop() * height / getWindowManager().getDefaultDisplay().getHeight(); dstWidth = (centerView.getRight() - centerView.getLeft())* width / getWindowManager().getDefaultDisplay().getWidth(); dstHeight = (centerView.getBottom() - centerView.getTop())* height / getWindowManager().getDefaultDisplay().getHeight(); } sfhCamera.AutoFocusAndPreviewCallback(); } } /** * 自動對焦後輸出圖片 */ private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() { @Override public void onPreviewFrame(byte[] data, Camera arg1) { //取得指定範圍的幀的資料 PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource( data, width, height, dstLeft, dstTop, dstWidth, dstHeight); //取得灰度圖 Bitmap mBitmap = source.renderCroppedGreyscaleBitmap(); //顯示灰度圖 imgView.setImageBitmap(mBitmap); BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source)); MultiFormatReader reader = new MultiFormatReader(); try { Result result = reader.decode(bitmap); String strResult = "BarcodeFormat:" + result.getBarcodeFormat().toString() + " text:" + result.getText(); txtScanResult.setText(strResult); } catch (Exception e) { txtScanResult.setText("Scanning"); } } };}</textarea>
SFHCamera.java是Camera控制類,原始碼如下:
<textarea cols="50" rows="15" name="code" class="java">package com.testCamera;import java.io.IOException;import android.graphics.PixelFormat;import android.hardware.Camera;import android.util.Log;import android.view.SurfaceHolder;public class SFHCamera implements SurfaceHolder.Callback{ private SurfaceHolder holder = null; private Camera mCamera; private int width,height; private Camera.PreviewCallback previewCallback; public SFHCamera(SurfaceHolder holder,int w,int h,Camera.PreviewCallback previewCallback) { this.holder = holder; this.holder.addCallback(this); this.holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); width=w; height=h; this.previewCallback=previewCallback; } @Override public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) { Camera.Parameters parameters = mCamera.getParameters(); parameters.setPreviewSize(width, height);//設定尺寸 parameters.setPictureFormat(PixelFormat.JPEG); mCamera.setParameters(parameters); mCamera.startPreview();//開始預覽 Log.e("Camera","surfaceChanged"); } @Override public void surfaceCreated(SurfaceHolder arg0) { mCamera = Camera.open();//啟動服務 try { mCamera.setPreviewDisplay(holder);//設定預覽 Log.e("Camera","surfaceCreated"); } catch (IOException e) { mCamera.release();//釋放 mCamera = null; } } @Override public void surfaceDestroyed(SurfaceHolder arg0) { mCamera.setPreviewCallback(null); mCamera.stopPreview();//停止預覽 mCamera = null; Log.e("Camera","surfaceDestroyed"); } /** * 自動對焦並回調Camera.PreviewCallback */ public void AutoFocusAndPreviewCallback() { if(mCamera!=null) mCamera.autoFocus(mAutoFocusCallBack); } /** * 自動對焦 */ private Camera.AutoFocusCallback mAutoFocusCallBack = new Camera.AutoFocusCallback() { @Override public void onAutoFocus(boolean success, Camera camera) { if (success) { //對焦成功,回撥Camera.PreviewCallback mCamera.setOneShotPreviewCallback(previewCallback); } } }; }</textarea>
其中testCamera.java的Camera.PreviewCallback previewCallback 是整個程式的邏輯核心,作為回撥函式給SFHCamera.java的內部Camera類呼叫。