安卓开发之调用摄像头、相册

这里抄的《第一行代码》源码,但是《第一行代码》在获取相册相片并裁剪时会出现问题

调用摄像头拍照,新建照片输出文件,创建Intent将拍照后的输出定向到该文件。

File outputImage = new File(Environment.getExternalStorageDirectory(), "tempImage.jpg");

imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);  //拍照后会返回结果到onActivityResult()方法 这里采用的是隐式intent,系统会自动查找能够执行操作的程序。

裁剪相片,

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);

注意添加SD卡写数据权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

调用相册相片并裁剪:

关于PICK和GET_CONTENT网上的说法是:

ACTION_PICK Android.intent.action.PICK 从列表中选择某项并返回所选数据

ACTION_GET_CONTENT Android.intent.action.GET_CONTENT 让用户选择数据,并返回所选数据(baiduzhidao)

If you want the user to choose something based on MIME type, use ACTION_GET_CONTENT.

If you have some specific collection (identified by a Uri) that you want the user to pick from, use ACTION_PICK.

In case of a tie, go with ACTION_GET_CONTENT. While ACTION_PICK is not formally deprecated, Dianne Hackborn recommends ACTION_GET_CONTENT.(stackoverflow)

 

File outputImage = new File(Environment.getExternalStorageDirectory(), "output_image.jpg");

imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.intent.action.PICK");  //第一行代码中采用的是GET_CONTENT,在裁剪时会出现照片无法读取的问题,注意获取本地存在的资源一律用PICK
intent.setType("image/*");
intent.putExtra("crop", true);
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PHOTO);  //第一行代码中直接跳转到CROP_PHOTO这样没有裁剪这个过程,实际裁剪实在TAKE_PHOTO这一case中执行的。

 

case TAKE_PHOTO:
if (resultCode == RESULT_OK)
{
if(data != null)
{
imageUri = data.getData();
}
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)
{
Log.e("test", "choose");
try
{
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
Log.e("test", "choose");
picture.setImageBitmap(bitmap);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
break;

posted @ 2015-12-20 21:56  雪贺  阅读(729)  评论(0编辑  收藏  举报