安卓调用相机和自定义相机SurfaceView实现预览

调用原生相机拍照:

private File file;
public void startCamera(View view) {
	Intent intent = new Intent();
	intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
	file = new File("/mnt/sdcard/my.jpg");
	intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
	startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	super.onActivityResult(requestCode, resultCode, data);
	if (requestCode==1) {
		Bitmap bitmap = BitmapFactory.decodeFile("/mnt/sdcard/my.jpg");
		iv.setImageBitmap(bitmap);
	}
}
自定义相机实现预览:

1、添加权限


2、布局

3、设置预览
SurfaceView sv = (SurfaceView) findViewById(R.id.sv);
holder = sv.getHolder();
holder.addCallback(new Callback() {	
	//当界面不可见的时候回调该方法
	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		if (camera!=null) {
			//停止预览
			camera.stopPreview();
			//释放资源
			camera.release();
			camera = null;
		}
	}
	//当 界面展现出来的时候回调
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (camera==null) {
			//打开照相机
			camera = Camera.open();
		}
		//开启预览
		camera.startPreview();
		try {
			//设置预览界面
			camera.setPreviewDisplay(holder);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
		
	}
});
4、实现拍照

if (camera!=null) {
	//参数1:拍照声音的回调
	//参数2:照片的原生的没有压缩过的数据
	//参数3:压缩过后的相片数据
	camera.takePicture(null, null, new PictureCallback() {
		//参数1:照片的字节码
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			try {
				//将data保存到sdcard上
				FileOutputStream fos = new FileOutputStream(new File("/mnt/sdcard/my2.jpg"));
				fos.write(data);
				fos.close();
				/*
				 * 需要重新开启预览,因此拍照的时候,系统会自动停止预览
				 */
				camera.startPreview();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	});
}
5、如果想自动对焦

//点击拍照按钮,摄像头自动对焦,对焦完成后拍照并保存
camera.autoFocus(new AutoFocusCallback() {
	@Override
	public void onAutoFocus(boolean success, Camera camera) {
	//对焦完成,拍照并保存
		camera.takePicture(null, null, new PictureCallback() {
			@Override
			public void onPictureTaken(byte[] data, Camera camera) {
			//设置照片保存路径
			String path =Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +UUID.randomUUID().toString() + ".jpg";
			try {
				FileOutputStream outputStream = new FileOutputStream(path);
				//将照片字节数组写到文件中
				outputStream.write(data);
				outputStream.close();
				//重新开启预览
				camera.startPreview();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	});
}


你可能感兴趣的:(android,Android,安卓,相机,自定义相机,SurfaceView)