class surface extends SurfaceView implements SurfaceHolder.Callback {
SurfaceHolder sfholder;
Camera camera;
Bitmap bitmap;
public surface(Context context) {
super(context);
// TODO Auto-generated constructor stub
sfholder = getHolder();
sfholder.addCallback(this);
sfholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(320, 480);
parameters.setPictureSize(320, 480);
camera.setParameters(parameters);
camera.startPreview();
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
try {
camera = Camera.open();
camera.setPreviewDisplay(sfholder);
} catch (Exception e) {
camera.release();
camera = null;
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera = null;
}
//拍照
public void takePicture()
{
if (camera != null)
{
camera.takePicture(null, null, jpegCallback);
}
}
//拍照并且保存的回调函数
private PictureCallback jpegCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
try
{
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
File file = new File("/sdcard/camera1.jpg");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
Canvas canvas= sfholder.lockCanvas();
canvas.drawBitmap(bitmap, 0,0, null);
sfholder.unlockCanvasAndPost(canvas);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
这个是一个拍照的类,使用的是SurfaceView来实现的,如果想要在一部分上显示,并且使用按钮操作的话,可以修改一下这个类,而且这个是拍照之后停留在拍照页面的,如果需要在拍照后不停留在拍照页面的,可以自行修改和添加参数。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
sf.takePicture();
return super.onKeyDown(keyCode, event);
}