Access pictures from Pictures app in my android app

人盡茶涼 提交于 2019-11-26 23:47:36

You can usestartActivityForResult, passing in an Intent that describes an action you want completed and and data source to perform the action on.

Luckily for you, Android includes an Action for picking things: Intent.ACTION__PICK and a data source containing pictures: android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI for images on the local device or android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI for images on the SD card.

Call startActivityForResult passing in the pick action and the images you want the user to select from like this:

startActivityForResult(new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI), SELECT_IMAGE);

Then override onActivityResult to listen for the user having made a selection.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == SELECT_IMAGE)
    if (resultCode == Activity.RESULT_OK) {
      Uri selectedImage = data.getData();
      // TODO Do something with the select image URI
    } 
}

Once you have the image Uri you can use it to access the image and do whatever you need to do with it.

You can also do:

Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

This will pick images across all storages.

Just an update to the answer given by Reto. You could do this to scale the image :

private String getPath(Uri uri) {
String[]  data = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, uri, data, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!