2015/10/13

Android Camera實現拍照功能

調用相機拍照時要先去偵測該手機支援到多高的解析度,否則會出現Runtime例外訊息
當拍照完會使相機停止預覽,需重新啟用預覽功能,可以在PictureCallback的尾段加上startPreview
相機要儲存的位置可以透過Environment去確認是否有插入記憶卡

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

    <SurfaceView
        android:id="@+id/surfaceView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/buttonTakePicture"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="拍照" />

</RelativeLayout>


Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cyfang.npust"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="19" />

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

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <activity android:name="com.cyfang.npust.CameraActivity" >
        </activity>
    </application>

</manifest>

Code:
package com.cyfang.npust;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CameraActivity extends Activity implements SurfaceHolder.Callback {
 private Button buttonTakePicture;
 private SurfaceView surfaceView;
 private SurfaceHolder surfaceHolder;
 private Camera camera;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_camera);
  this.buttonTakePicture = (Button) findViewById(R.id.buttonTakePicture);
  this.buttonTakePicture.setOnClickListener(clickListener);
  this.surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
  this.surfaceHolder = this.surfaceView.getHolder();
  this.surfaceHolder.addCallback(this);
  this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
 }

 private Button.OnClickListener clickListener = new OnClickListener() {
  @Override
  public void onClick(View v) {
   if (camera != null) {
    camera.takePicture(null, null, pictureCallBack);
   }
  }
 };

 private PictureCallback pictureCallBack = new PictureCallback() {
  @Override
  public void onPictureTaken(byte[] data, Camera camera) {
   try {

    // 設定檔案存放位置
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/",
      new Date().getTime() + ".jpg");
    FileOutputStream fileOutputStream = new FileOutputStream(file);

    // 進行解碼
    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

    // 圖片壓縮
    bitmap.compress(CompressFormat.JPEG, 85, fileOutputStream);

    // 寫入檔案
    fileOutputStream.flush();
    fileOutputStream.close();

    // 重新開啟預覽
    camera.startPreview();
   } catch (FileNotFoundException e) {
   } catch (IOException e) {

   }

  }
 };

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

   // 取得相機參數
   Camera.Parameters parameters = camera.getParameters();

   List previewList = parameters.getSupportedPreviewSizes();
   List pictureList = parameters.getSupportedPictureSizes();

   // 設定最佳照片尺寸
   parameters.setPictureSize(pictureList.get(0).width, pictureList.get(0).height);
   
   // 設定最佳預覽尺寸
   parameters.setPreviewSize(previewList.get(0).width, previewList.get(0).height);

   // 設定相機參數
   this.camera.setParameters(parameters);

   // 轉向90度
   this.camera.setDisplayOrientation(90);

   // 設定顯示的Holder
   this.camera.setPreviewDisplay(surfaceHolder);

   // 開始顯示
   this.camera.startPreview();

  } catch (IOException e) {

  } catch (RuntimeException e) {
   // 照片尺寸太大會使程式出現Runtime Exception
  }
 }

 @Override
 public void surfaceCreated(SurfaceHolder holder) {
  // 開啟相機功能
  this.camera = Camera.open();
 }

 @Override
 public void surfaceDestroyed(SurfaceHolder holder) {
  // 停止相機預覽
  this.camera.stopPreview();

  // 釋放相機資源
  this.camera.release();
  this.camera = null;
 }

}