1、布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<SurfaceView
android:id="@+id/main_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:text="拍照" />
</LinearLayout>
2、Activity
public class MainActivity extends Activity {
private Button btn;
private SurfaceView mainView;
private String tempName = "temp.jpg";
private Camera c;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.btn);
mainView = (SurfaceView) findViewById(R.id.main_view);
SurfaceHolder holder = mainView.getHolder();
c = Camera.open();
holder.addCallback(new Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// 加入一个初始化属性
Parameters p = c.getParameters();
// 设置相机所对应的预览区域
try {
c.setDisplayOrientation(90);
c.setPreviewDisplay(holder);
} catch (Exception e) {
e.printStackTrace();
}
// 开始预览
c.startPreview();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
c.takePicture(null, null, new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
c.stopPreview();
FileOutputStream os = new FileOutputStream(
new File(Environment
.getExternalStorageDirectory(),
tempName));
os.write(data);
os.close();
c.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
}
@Override
protected void onDestroy() {
if (c != null) {
try {
c.release();
} catch (Exception e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}