系统已经有的东西,如果我们没有新的需求的话,直接调用是最直接的。下面讲讲调用系统相机拍照并保存图片和如何调用系统相册的方法。
首先看看调用系统相机的核心方法:
-
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
-
startActivityForResult(camera, 100);
相机返回的数据通过下面的回调方法取得,并处理
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == CAMERA && resultCode == Activity.RESULT_OK && null != data){ Bundle bundle = data.getExtras(); //获取相机返回的数据,并转换为图片格式 Bitmap bitmap = (Bitmap)bundle.get("data"); } }
下面是调用系统相册并取得照片的方法:
-
Intent picture = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
-
startActivityForResult(picture, 101);
- 或者
- intent = new
Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(intent, 101);
下面是相应的回调方法:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == 101 && resultCode == Activity.RESULT_OK && null != data){ Uri selectedImage = data.getData(); String[] filePathColumns={MediaStore.Images.Media.DATA}; Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,null, null); c.moveToFirst(); int columnIndex = c.getColumnIndex(filePathColumns[0]); String picturePath= c.getString(columnIndex); c.close(); }
}
或者
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case 101: Uri uri = data.getData(); Cursor cursor = this.getContentResolver().query(uri, null, null, null, null); cursor.moveToFirst(); String imgNo = cursor.getString(0); // 图片编号
String imgPath = cursor.getString(1); // 图片文件路径
String imgSize = cursor.getString(2); // 图片大小
String imgName = cursor.getString(3); // 图片文件名
cursor.close(); Bitmap bitmap = BitmapFactory.decodeFile(imgPath);
break; default: return; } } }