2016年6月8日 星期三

Android 中使用 Camera 預覽

出處


Android 中使用 Camera

1. 在 AndroidManifest.xml 中加上 permission 和 feature

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


2. 再來在 layout 中加上 SurfaceView


<SurfaceView
android:id="@+id/surfaceView1"
android:layout_width="320px"
android:layout_height="240px">
</SurfaceView>

3. 程式碼

參考 Android SDK 網頁
http://developer.android.com/reference/android/hardware/Camera.html
下面是範例code


package newslab.video.server;

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class VideoServer extends Activity implements SurfaceHolder.Callback {
TextView testView;

Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;

private final String tag = "VideoServer";

Button start, stop;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        start = (Button)findViewById(R.id.btn_start);
        start.setOnClickListener(new Button.OnClickListener()
        {
public void onClick(View arg0) {
start_camera();
}
        });
        stop = (Button)findViewById(R.id.btn_stop);
        stop.setOnClickListener(new Button.OnClickListener()
        {
public void onClick(View arg0) {
stop_camera();
}
        });
      
        surfaceView = (SurfaceView)findViewById(R.id.surfaceView1);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }
  
    private void start_camera()
    {
     try{
     camera = Camera.open();
     }catch(RuntimeException e){
     Log.e(tag, "init_camera: " + e);
     return;
     }
     Camera.Parameters param;
     param = camera.getParameters();
     //modify parameter
     param.setPreviewFrameRate(20);
     param.setPreviewSize(176, 144);
     camera.setParameters(param);
     try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
} catch (Exception e) {
Log.e(tag, "init_camera: " + e);
return;
}
    }
  
    private void stop_camera()
    {
     camera.stopPreview();
     camera.release();
    }

public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}

public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}

public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}


startPreview 之後 就可以看是要照像還是拍影片了

沒有留言:

張貼留言