Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Camera2進行掃碼解析

Camera2進行掃碼解析

編輯:關於Android編程

Camera2是5.0後的api,網上暫時沒找到對於Camera2進行掃碼解析的代碼。

寫此文純粹為了個人日後方便查詢。

package com.example.one.codescanm;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.media.Image;
import android.media.ImageReader;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Hashtable;

public class MainActivity extends Activity {

    private CameraManager cameraManager;
    private String camerid;
    private Handler handler;
    private SurfaceHolder holder;
    private CaptureRequest.Builder build;
    private ImageReader imageReader;
    private SurfaceView surfaceView;
    private ImageView imageView;
    private Bitmap bitmap2;
    private CameraCaptureSession msession;
    private CameraDevice cameraDevice;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView= (ImageView) findViewById(R.id.ada);
        surfaceView= (SurfaceView) findViewById(R.id.surface);
        holder=surfaceView.getHolder();
        cameraManager= (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        camerid=CameraCharacteristics.LENS_FACING_FRONT+"";
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                imageReader=ImageReader.newInstance(surfaceView.getWidth(),surfaceView.getHeight(),ImageFormat.JPEG,7);
                HandlerThread handlerThread=new HandlerThread("Camera2");
                handlerThread.start();
                handler=new Handler(handlerThread.getLooper());
                try {
                    cameraManager.openCamera(camerid,new MyDeviceStateCallBack(),handler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }catch (SecurityException e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {

            }
        });
    }
    class MyDeviceStateCallBack extends CameraDevice.StateCallback
    {

        @Override
        public void onOpened(CameraDevice camera) {
            cameraDevice=camera;
            try {
                build=camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                build.addTarget(holder.getSurface());
                camera.createCaptureSession(Arrays.asList(holder.getSurface(),imageReader.getSurface()),new MySessionStateCallBack(),handler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onDisconnected(CameraDevice camera) {

        }

        @Override
        public void onError(CameraDevice camera, int error) {

        }
    }
    class MySessionStateCallBack extends CameraCaptureSession.StateCallback
    {
        @Override
        public void onConfigured(CameraCaptureSession session) {
            build.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            try {
                session.setRepeatingRequest(build.build(),new MySessionCaptureCallBack(),handler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onConfigureFailed(CameraCaptureSession session) {

        }
    }
    class MySessionCaptureCallBack extends CameraCaptureSession.CaptureCallback
    {
        @Override
        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
            Log.d("ma",result.get(CaptureResult.CONTROL_AF_STATE)+"/////");
            msession=session;
            //在聚焦完成後進行自動捕捉圖片
            if(result.get(CaptureResult.CONTROL_AF_STATE)==CaptureRequest.CONTROL_AF_STATE_PASSIVE_FOCUSED)
            {
                //捕捉圖片
                build.set(CaptureRequest.CONTROL_AF_TRIGGER,CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
                build.addTarget(imageReader.getSurface());
                try {
                    session.setRepeatingRequest(build.build(), new CameraCaptureSession.CaptureCallback() {
                        @Override
                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                            super.onCaptureCompleted(session, request, result);
                            if(imageReader!=null)
                            {
                                Image image=imageReader.acquireLatestImage();
                                if(image!=null)
                                {
                                    try {
                                        //獲取到圖片後停止捕捉
                                        session.stopRepeating();
                                    } catch (CameraAccessException e) {
                                        e.printStackTrace();
                                    }
                                    Image.Plane[] planes=image.getPlanes();
                                    ByteBuffer byteBuffer=planes[0].getBuffer();
                                    byte[] bytes=new byte[byteBuffer.remaining()];
                                    byteBuffer.get(bytes);
                                    bitmap2=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
                                    myHandler.sendEmptyMessage(1);
                                }
                            }
                        }
                    },handler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    Handler myHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            imageView.setImageBitmap(bitmap2);
            //解析二維碼
            MyLuminanceSource myLuminanceSource=new MyLuminanceSource(bitmap2);
            Hashtable hashtable=new Hashtable<>();
            hashtable.put(DecodeHintType.CHARACTER_SET,"UTF-8");
            BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(myLuminanceSource));
            QRCodeReader qrCodeReader=new QRCodeReader();
            Result result= null;
            try {
                result = qrCodeReader.decode(binaryBitmap,hashtable);
            } catch (NotFoundException e) {
                e.printStackTrace();
            } catch (ChecksumException e) {
                e.printStackTrace();
            } catch (FormatException e) {
                e.printStackTrace();
            }
            if(result==null)
            {
                try {
                    //stopRepeating()並不能解除TRIGGER狀態所以先進行解除不然在回調時無法獲取CONTROL_AF_STATE_PASSIVE_FOCUSED狀態
                    build=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                    build.addTarget(holder.getSurface());
                    build.set(CaptureRequest.CONTROL_AF_TRIGGER,CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL);
                    msession.setRepeatingRequest(build.build(), new CameraCaptureSession.CaptureCallback() {
                        @Override
                        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                            super.onCaptureCompleted(session, request, result);
                            try {
                                session.stopRepeating();
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                            try {
                                build=cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                            build.addTarget(holder.getSurface());
                            build.set(CaptureRequest.CONTROL_AF_MODE,CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                            try {
                                msession.setRepeatingRequest(build.build(), new MySessionCaptureCallBack(), handler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    }, handler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    };
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved