How to get last image captured with camera in andr

2019-05-26 22:32发布

问题:

This question already has an answer here:

  • get the last picture taken by user 2 answers

My intention is not to take a picture and then save it to sd card , get the link and all. The image is already taked with the original camera app in the android.

All i need it how can i get that image path with respect to sd card like

emulated/0/sdcard/DCIM/100ANDRO/image.jpg

how do i get that format of the recently taken image.

回答1:

Use this to get path of file from URI:

Uri selectedImageUri = data.getData();
selectedImagePath = getRealPathFromURI(selectedImageUri);

    public String getRealPathFromURI(Context context, Uri contentUri) {
  Cursor cursor = null;
  try { 
    String[] proj = { MediaStore.Images.Media.DATA };
    cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
  } finally {
    if (cursor != null) {
      cursor.close();
    }
  }
}

Cursor provides random read-write access to the result set returned by a database query.

getContentResolver () returns a ContentResolver instance for your application's package.

When you want to access data in a content provider, you use the ContentResolver object in your application's Context to communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.

The Content Resolver includes the CRUD (create, read, update, delete) methods corresponding to the abstract methods (insert, delete, query, update) in the Content Provider class. The Content Resolver does not know the implementation of the Content Providers it is interacting with (nor does it need to know); each method is passed an URI that specifies the Content Provider to interact with.

MediaStore: The Media provider contains meta data for all available media on both internal and external storage devices. MediaStore.images contains meta data for all available images.



回答2:

I've accomplished it like this:

final String[] imageColumns = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
Cursor imageCursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, imageColumns, null, null, imageOrderBy);
imageCursor.moveToFirst();
do {
    String fullPath = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
    if (fullPath.contains("DCIM")) {
        //--last image from camera --
        return;
    }
}
while (imageCursor.moveToNext());