Camera2进行扫码解析

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<DecodeHintType,String> 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();
                }
            }
        }
    };
}

你可能感兴趣的:(扫描二维码,camera2)