Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自訂相機拍照:Camera API 的完整流程與程式碼實作

編輯:關於 Android 程式設計

如果只是想低調地調起系統相機,一個 ACTION_IMAGE_CAPTURE 的 Intent 就足夠。但當需求變成「畫面必須全螢幕」、「要拿到原始資料自行處理」、「要控制對焦與曝光」,就得直接操作 Camera API。以下把整個流程與實作完整走一遍。

六個基本步驟

1. 呼叫 Camera.open() 開啟相機。

2. 呼叫 getParameters() 取得 Camera.Parameters 物件。

3. 透過 Parameters 的 setter 設定解析度、格式、畫質、預覽參數等。

4. 先 setPreviewDisplay(SurfaceHolder) 指定取景畫面要畫在哪個 SurfaceView,再呼叫 startPreview() 開始預覽。

5. 呼叫 takePicture() 進行拍照。

6. 結束時 stopPreview() 停止預覽,並 release() 釋放硬體資源。

第六步最容易被忽略。相機是獨佔裝置,沒有確實 release,下次開啟就會拿到 CameraOpen 失敗。

權限宣告

<uses-permission android:name="android.permission.CAMERA" />

取景版面:activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <SurfaceView
        android:id="@+id/sView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/take"
        android:layout_alignParentBottom="true"
        android:onClick="capture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/take" />
</RelativeLayout>

存檔對話框版面:save.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/photoNmae"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/show"
        android:layout_below="@id/photoNmae"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

主程式

package com.android.xiong.cameratest;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {
    private SurfaceView sView;
    private SurfaceHolder surfaceHodler;
    private int screenWidth, screenHeight;

    private Camera camera;      // 系統相機
    private boolean isPreview = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

        // 取得螢幕寬高
        WindowManager wm = getWindowManager();
        Display display = wm.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        screenWidth = metrics.widthPixels;
        screenHeight = metrics.heightPixels;

        sView = (SurfaceView) findViewById(R.id.sView);
        // 由 Surface 自行維護緩衝區
        sView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceHodler = sView.getHolder();
        surfaceHodler.addCallback(new Callback() {
            @Override
            public void surfaceDestroyed(SurfaceHolder arg0) {
                // 視圖銷毀時務必釋放相機
                if (camera != null) {
                    if (isPreview) camera.stopPreview();
                    camera.release();
                    camera = null;
                }
                isPreview = false;
            }

            @Override
            public void surfaceCreated(SurfaceHolder arg0) {
                initCamera();
            }

            @Override
            public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
            }
        });
    }

    private void initCamera() {
        if (!isPreview) {
            // 不帶參數預設開啟後置相機;想要前置可傳 Camera.CameraInfo.CAMERA_FACING_FRONT
            camera = Camera.open();
            camera.setDisplayOrientation(90);
        }
        if (!isPreview && camera != null) {
            Camera.Parameters parameters = camera.getParameters();
            parameters.setPreviewSize(screenWidth, screenHeight);
            // 預覽每秒顯示影格數的最小與最大值
            parameters.setPreviewFpsRange(4, 10);
            parameters.setPictureFormat(ImageFormat.JPEG);
            parameters.set("jpeg-quality", 85);
            parameters.setPictureSize(screenWidth, screenHeight);
            try {
                camera.setPreviewDisplay(surfaceHodler);
            } catch (IOException e) {
                e.printStackTrace();
            }
            camera.startPreview();
            isPreview = true;
        }
    }

    /** 點擊快門:先對焦,對焦成功後才真正拍照 */
    public void capture(View source) {
        if (camera != null) {
            camera.autoFocus(autoFocusCallback);
        }
    }

    AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            if (success) {
                // takePicture 需要三個監聽器:
                // 1. ShutterCallback:按下快門瞬間觸發
                // 2. PictureCallback:取得原始(未壓縮)資料時觸發
                // 3. PictureCallback:取得 JPEG 資料時觸發
                camera.takePicture(new ShutterCallback() {
                    @Override
                    public void onShutter() {
                    }
                }, new PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] arg0, Camera arg1) {
                        // 這裡可決定是否保留原始資料
                    }
                }, myJpegCallback);
            }
        }
    };

    PictureCallback myJpegCallback = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            final Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);

            View saveDialog = getLayoutInflater().inflate(R.layout.save, null);
            final EditText potoName = (EditText) saveDialog.findViewById(R.id.photoNmae);
            ImageView show = (ImageView) saveDialog.findViewById(R.id.show);
            show.setImageBitmap(bm);

            new AlertDialog.Builder(MainActivity.this)
                    .setView(saveDialog)
                    .setNegativeButton("取消", null)
                    .setPositiveButton("保存", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            File file = new File(Environment.getExternalStorageDirectory()
                                    + "/" + potoName.getText().toString() + ".jpg");
                            FileOutputStream fileOutStream = null;
                            try {
                                fileOutStream = new FileOutputStream(file);
                                bm.compress(CompressFormat.JPEG, 100, fileOutStream);
                                fileOutStream.close();
                            } catch (IOException io) {
                                io.printStackTrace();
                            }
                        }
                    }).show();

            // 恢復預覽,讓使用者可以繼續拍
            camera.stopPreview();
            camera.startPreview();
            isPreview = true;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

實作上的幾個關鍵點

顯示方向。setDisplayOrientation(90) 之所以必要,是因為感測器座標與螢幕座標預設相差 90 度;不設定就會拍出「畫面是橫的、照片是躺的」。建議依裝置自然方向動態計算,而非寫死角度。

大圖記憶體。直接 decodeByteArray 全尺寸 JPEG 在解析度高的機型上很容易 OOM。實務上會先用 BitmapFactory.Options 的 inJustDecodeBounds 讀取尺寸,再決定 inSampleSize 做降採樣。

API 演進。Camera 這套 API 自 Android 5.0 起已被 Camera2 取代,新版提供 Level 3 的 RAW 輸出、手動 ISO/快門與更精細的請求控制。新專案建議直接採用 Camera2 或 CameraX;上述程式碼則適合維護既有專案或理解底層拍照流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved