Andoid 调用相机程序获取图片
标签: Android
- 启动相机程序(打开相机程序)
imageUri = Uri.fromFile(outputFile);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,TAKE_PHOTO);
intent传递了一个数据 MediaStore.EXTRA_OUTPUT
API文档:
public static final String EXTRA_OUTPUT
Added in API level 3 The name of the Intent-extra used to indicate a content resolver Uri to be used to store the requested image or video.
指明一个内容接收地址用于存放图片或视频。
- 拍摄完成的图片裁剪操作
/*使用startActivityForResult启动程序结束后会调用此方法*/
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode){
case TAKE_PHOTO:
if (resultCode==RESULT_OK){
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri,"image/*");//提供操作数据,要裁剪的图片位置
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);//图片的保存位置
startActivityForResult(intent,CROP_PHOTO);//启动裁剪程序
}
break;
case CROP_PHOTO:
if (resultCode==RESULT_OK){
try {
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
break;
default:
break;
}
}
}
- Intent的Data与Type属性
- Data属性通常用于向Action属性提供操作的数据,Data属性接受一个Uri对象
- Type属性则用于明确指定Data属性的数据类型或MIME类型,但是通常来说,当Intent不指定Data属性时Type属性才会起作用,否则Android系统将会根据Data属性值来分析数据的类型,所以无需指定Type属性。
API文档:
public Intent setDataAndType (Uri data, String type)
Added in API level 1
(Usually optional) Set the data for the intent along with an explicit MIME data type. This method should very rarely be used – it allows you to override the MIME type that would ordinarily be inferred from the data with your own type given here.
使用的概率非常少,谷歌认为使用这个并没有什么必要。
Note: MIME type and Uri scheme matching in the Android framework is case-sensitive, unlike the formal RFC definitions. As a result, you should always write these elements with lower case letters, or use normalizeMimeType(String) or normalizeScheme() or setDataAndTypeAndNormalize(Uri, String) to ensure that they are converted to lower case.