相機實作

      在〈相機實作〉中尚無留言

Camera3D.java

public class Camera3D {
    Context context;
    CameraManager manager;
    private Size size;
    private CameraDevice camera;
    private HandlerThread handlerThread;
    private Handler handler;
    CaptureRequest.Builder captureBuilder;
    @SuppressWarnings("MissingPermission")
    public Camera3D(Context context){
        this.context=context;
        handlerThread=new HandlerThread("Camera2");
        handlerThread.start();
        handler=new Handler(handlerThread.getLooper());
        manager=(CameraManager)context.getSystemService(Context.CAMERA_SERVICE);
        try {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics("0");
            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            size=map.getOutputSizes(SurfaceTexture.class)[0];
            manager.openCamera("0", mDeviceCallback, handler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    public void startPreview(SurfaceTexture view){
        Surface surface=new Surface(view);
        try {
            captureBuilder = camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            captureBuilder.addTarget(surface);
            camera.createCaptureSession(Arrays.asList(surface), mSessionCallback, handler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private CameraDevice.StateCallback mDeviceCallback=new CameraDevice.StateCallback(){
        @Override
        public void onOpened(CameraDevice cameraDevice) {
            camera=cameraDevice;
        }
        @Override
        public void onDisconnected(CameraDevice cameraDevice) {}
        @Override
        public void onError(CameraDevice cameraDevice, int i) {}
    };
    private CameraCaptureSession.StateCallback mSessionCallback=new CameraCaptureSession.StateCallback(){
        @Override
        public void onConfigured(CameraCaptureSession session) {
            try {
                captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                captureBuilder.set(CaptureRequest.CONTROL_AE_MODE,
                        CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                session.setRepeatingRequest(captureBuilder.build(), mCaptureCallBack, handler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
        @Override
        public void onConfigureFailed(CameraCaptureSession session) {}
    };
    private CameraCaptureSession.CaptureCallback mCaptureCallBack=new CameraCaptureSession.CaptureCallback(){
        @Override
        public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
        }
        @Override
        public void onCaptureProgressed(CameraCaptureSession session, CaptureRequest request, CaptureResult partialResult) {
        }
    };
}

MainActivity.java

public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
    private final int REQUEST_CAMERA_PERMISSION=100;
    TextureView textureView;
    Camera3D camera;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN );
        setContentView(R.layout.activity_main);
        processPermission();
    }
    private void processPermission(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            int hasPermission=checkSelfPermission(Manifest.permission.CAMERA);
            if(hasPermission!= PackageManager.PERMISSION_GRANTED){
                requestPermissions(
                        new String[]{Manifest.permission.CAMERA},
                        REQUEST_CAMERA_PERMISSION);
                return;
            }
            else{
                init();
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(
            int requestCode,
            @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        if(requestCode==REQUEST_CAMERA_PERMISSION){
            if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
                init();
            }
            else{
                Toast.makeText(this, "No permission", Toast.LENGTH_LONG).show();
            }
        }
        else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    public void init(){
        textureView=(TextureView)findViewById(R.id.textureView);
        camera=new Camera3D(this);
        textureView.setSurfaceTextureListener(this);
    }
    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        camera.startPreview(surfaceTexture);
    }
    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {}
    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        return false;
    }
    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {}
}

設定檔

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.ddns.mahaljsp.camera3d">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.FLASHLIGHT" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera2" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:theme="@style/Theme.AppCompat.Light.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

完整程式碼下載 : Camera3D.rar

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *