系統已經有的東西,如果我們沒有新的需求的話,直接調用是最直接的。下面講講調用系統相機拍照並保存圖片和如何調用系統相冊的方法。
首先看看調用系統相機的核心方法:
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;
}
}
}