代码改变世界

android 调用系统摄像头

2011-07-14 14:00  蓝之风  阅读(2228)  评论(1编辑  收藏  举报

在开发android 应用的时候我们经常需要用到摄像头来进行拍照或者是录制视频,这里介绍一种最简单的方法:调用系统摄像头来拍照,并将照片保存起来

启动摄像头的方法:

startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);

拍摄成功后接收参数的接收方法我们只需要重写

protected void onActivityResult(int requestCode, int resultCode, Intent data)方法即可

如:

final int TAKE_PICTURE = 1;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == TAKE_PICTURE) {
			if (resultCode == RESULT_OK) {
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				imgPhoto.setImageBitmap(bm);// ??¨ª?????¨º??¨²ImageView¨º¨®¨ª?¨¦?¡ê?private
				// ¡ä?¡ä|?D??¡ä?¡ä¡é?¡§¨º?¡¤?¡ä??¨²
				sdCardExit = Environment.getExternalStorageState().equals(
						android.os.Environment.MEDIA_MOUNTED);					// ImageView img;
				if (sdCardExit) {
					myRecAudioDir = new File(Environment
							.getExternalStorageDirectory().getAbsolutePath()
							+ "/custom_picture");
					if (!myRecAudioDir.exists()) {
						myRecAudioDir.mkdir();
					}
				} else {
					mMakeTextToast("¡ä?¡ä¡é?¡§2?¡ä??¨²", true);
				}
				try {
					File f = File.createTempFile(strTempFile, ".jpg",
							myRecAudioDir);

					BufferedOutputStream bos = new BufferedOutputStream(
							new FileOutputStream(f));
					photoPath=f.getPath();
					/* 2¨¦¨®??1??¡Áa¦Ì¦Ì¡¤?¡¤¡§ */
					bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);

					/* ¦Ì¡Â¨®?flush()¡¤?¡¤¡§¡ê??¨¹D?BufferStream */
					bos.flush();

					/* ?¨¢¨º?OutputStream */
					bos.close();
				} catch (FileNotFoundException e) {					
					e.printStackTrace();
				} catch (IOException e) {					
					e.printStackTrace();
				}
			}
		}
	}
拍摄效果如下图:
image 
返回结果如下图:
image