`

调用系统照相机,将照片保存在SDK上,并将照片赋值给一个ImageView显示出来

 
阅读更多

定义一个照相机类CameraOneActivityActivity,这个类中有一个Button一个ImageView

 

public class CameraOneActivityActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.camera);

		Button button = (Button) findViewById(R.id.button);

		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 1);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == Activity.RESULT_OK) {

			String sdStatus = Environment.getExternalStorageState();
			// 检测sd是否可用
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { 
				
				Log.v("TestFile",
						"SD card is not avaiable/writeable right now.");
				return;
			}

			Bundle bundle = data.getExtras();
			// 获取相机返回的数据,并转换为Bitmap图片格式
			Bitmap bitmap = (Bitmap) bundle.get("data");
			FileOutputStream b = null;
			File file = new File("/sdcard/myImage/");
			// 创建文件夹
			file.mkdirs();

			// 将时间命名为照片的名字
			String str = null;
			Date date = null;
			// 获取当前时间,进一步转化为字符串
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd-HH-mm-ss");
			date = new Date();
			str = format.format(date);
			//以时间的名字保存在SDK下,并且格式为JPG
			String fileName = "/sdcard/myImage/" + str + ".jpg";

			try {
				b = new FileOutputStream(fileName);
				// 把数据写入文件
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 将图片显示在ImageView里
			((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);
		}
	}
}

 

定义界面的camer.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
     <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="点击启动相机" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#999999" />
</LinearLayout>

 以上代码就是系统调用一个照相机并将照片赋值给一个ImageView,并将照片保存在Sd卡下 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics