CameraEx.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
//카메라의 제어
public class CameraEx extends Activity {
//애플리케이션 초기화
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new CameraView(this));
}
}
CameraView.java
import android.content.Context;
import android.hardware.Camera;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.FileOutputStream;
//카메라의 제어
public class CameraView extends SurfaceView
implements SurfaceHolder.Callback {
private SurfaceHolder holder;//홀더
private Camera camera;//카메라
//생성자
public CameraView(Context context) {
super(context);
// SurfaceHolder 생성
holder=getHolder();
holder.addCallback(this);
// Push Buffer 지정
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
//Surface 생성시 호출
public void surfaceCreated(SurfaceHolder holder) {
//카메라의 초기화
try {
camera=Camera.open();
camera.setPreviewDisplay(holder);
} catch (Exception e) {
}
}
//Surface 변경 이벤트 처리
public void surfaceChanged(SurfaceHolder holder,int format,int w,int h) {
// 카메라의 리뷰 개시
Camera.Parameters parameters=camera.getParameters();
parameters.setPreviewSize(w,h);
camera.setParameters(parameters);
camera.startPreview();
}
//Surface 해제 이벤트 처리
public void surfaceDestroyed(SurfaceHolder holder) {
//카메라 프리뷰의 개시
camera.setPreviewCallback(null);
camera.stopPreview();
camera.release();
camera=null;
}
//터치 이벤트 처
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
takePicture();
camera.startPreview();
}
return true;
}
//사진 촬영
public void takePicture() {
//카메라의 스크린샷 취득
camera.takePicture(null,null,new Camera.PictureCallback() {
public void onPictureTaken(byte[] data,Camera camera) {
try {
data2sd(getContext(),data,"test.jpg");
} catch (Exception e) {
android.util.Log.e("",""+e.toString());
}
}
});
}
//바이트 데이터 -> SD 카드
private static void data2sd(Context context,
byte[] w,String fileName) throws Exception {
//SD카드의 데이터 저장
FileOutputStream fos=null;
try {
fos=new FileOutputStream("/sdcard/"+fileName);
fos.write(w);
fos.close();
} catch (Exception e) {
if (fos!=null) fos.close();
throw e;
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="net.npaka.cameraex"
android:versionCode="1"
android:versionName="1.0.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".CameraEx"
android:label="@string/app_name" android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA" />
</manifest>