get the last picture taken by user - android

hey I want to get the last picture captured by user through any camera application.
I have no idea how to do that
can any one help me?
further I want to send that image as an attachment to an email or MMS..
thanks

// Find the last picture
String[] projection = new String[]{
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.MIME_TYPE
};
final Cursor cursor = getContext().getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
// Put it in the image view
if (cursor.moveToFirst()) {
final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
String imageLocation = cursor.getString(1);
File imageFile = new File(imageLocation);
if (imageFile.exists()) { // TODO: is there a better way to do this?
Bitmap bm = BitmapFactory.decodeFile(imageLocation);
imageView.setImageBitmap(bm);
}
}
I'm still working on the MMS sending part.

Inspired by https://stackoverflow.com/a/20065920/763459
So the main concern in that answer was not all the devices are using "DCIM" as the camera folder. Then I found out that if a file is located inside a app-specified folder, it will be indexed by ContentResolver but the other app doesn't have access to it, which means canRead=false. So here I come up with another solution:
while (cursor.moveToNext()) {
String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
File imageFile = new File(imagePath);
if (imageFile.canRead() && imageFile.exists()) {
// we have found the latest picture in the public folder, do whatever you want
break;
}
}

Here it is in Kotlin. I have used Glide library to load the last image into an imageview
private fun getLastImageFromGallery(){
val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.Media._ID,
MediaStore.Images.ImageColumns.DATE_ADDED,
MediaStore.Images.ImageColumns.MIME_TYPE
)
val cursor: Cursor = applicationContext.contentResolver.query(uriExternal, projection, null,
null, MediaStore.Images.ImageColumns.DATE_ADDED + " DESC"
)!!
Log.i("Cursor Last", cursor.moveToLast().toString())
if (cursor.moveToFirst()) {
val columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val imageId: Long = cursor.getLong(columnIndexID)
val imageURI = Uri.withAppendedPath(uriExternal, "" + imageId)
Glide.with(applicationContext)
.load(imageURI)
.transform(CenterCrop(), RoundedCorners(12))
.into(imageView)
}
cursor.close()
}

Related

How share images/videos in custom folders using ContentResolver/ or other way in Android ? Getting FileUriExposedException Exception

I have a custom folder in the Pictures directory, like this Pictures/MyFolder. It has images in MyFolder. Here is how to share the images using ContentResolver on MyFolder only. Or is any alternative ways to share the image. It is on android 11.
I queried images using the following snippets
String[] projection = new String[]{
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
MediaStore.Images.Media.DATE_TAKEN};
Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;
Cursor cur = context.getContentResolver().query(images,
projection, // Which
// columns
// to return
null, // Which rows to return (all rows)
null, // Selection arguments (none)
orderBy + " DESC" // Ordering
);
int bucketColumn = cur.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);
int dateColumn = cur.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN);
do {
bucket = cur.getString(bucketColumn);
if (bucket.equals(context.getString(R.string.app_name))) {
date = cur.getString(dateColumn);
imagePath = listImageByFolder.get(bucket);
if (imagePath == null) {
imagePath = new ArrayList<String>();
}
imagePath.add(cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA)));
Uri x = Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, String.valueOf(cur.getString(cur.getColumnIndex(MediaStore.Images.Media.DATA))));
listImageByFolder.put(bucket, imagePath);
} ;
} while (cur.moveToNext());
While I try to share the image, Getting android.os.FileUriExposedException: file:///storage/emulated/0/Pictures/WhatsTouch/1628090801008.jpg exposed beyond app through ClipData.Item.getUri() exception. Is any way to correct it or is any alternative way?

Media Gallery ContentProvider

My app will display the complete list of images in my custom gallery .For this, I'm using ContentProvider of Image Thumbnails. Upon selecting the thumbnail's I need to display the actual image.According to my understanding Gallery's image do have same unique ID in Thumb and Media Table.
Here is the code. Firstly I queried Thumbnail's ContentProvider and saved URL and ID.
String pictureThumbTemp[] = { MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA };
Cursor imagecursor = context.getContentResolver().query (MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
pictureThumbTemp,null, null, null);
Later I am displaying thumbs in Grid.
Upon selection of thumbnail, I have to display original image. I'm trying to retrieve the original image like
String pictureImageTemp[] = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor imagecursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
pictureImageTemp, MediaStore.Images.Media._ID + " = " + mediaID + "", null,
MediaStore.Images.Media._ID);
Overall, I'm showing thumbnail through it's url and upon click I'm querying the thumbnail's media ID in Original image table.
But it is returning a cursor with 0 results.
Please help me out.
Thanks,
sha.
I cracked out a way which worked out.
Retrieved the cursor for Original Images.
From that I pulled the ID for every image and Queried the Thumbnails for the ID which returns a cursor containing paths.
Find the code snippet below.
String pictureCols[] = { MediaStore.Images.Media._ID, MediaStore.Images.Media.DATA };
Cursor imagecursor = mContext.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureCols,
null, null, null);
imagecursor.moveToFirst();
mImageUrls = new ArrayList<String>();
try {
// Iterate the cursor for Image urls
for (int index = 0; index < imagecursor.getCount(); index++) {
imagecursor.moveToPosition(index);
preparePicture(imagecursor);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
imagecursor.close();
}
}
Here is the code for preparePicture method
private void preparePicture(Cursor imageCursor) {
// get the ID for the original image
int idColumnIndex = imageCursor.getColumnIndex(mSelectedImage.mediaID);
Long id = imageCursor.getLong(idColumnIndex);
// Thumbnail image Cursor for this specific image.
String thumbCols[] = { MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA };
Cursor thumbCursor = MediaStore.Images.Thumbnails.queryMiniThumbnail(mContext.getContentResolver(), id,
Thumbnails.MINI_KIND, thumbCols);
thumbCursor.moveToFirst();
// Save thumbnail URL in MediaInfo
dataColumnIndex = thumbCursor.getColumnIndex(mSelectedThumb.data);
String thumbURL = thumbCursor.getString(dataColumnIndex);
thumbCursor.close();
mImageUrls.add(url);
}
Finally, I will have all my Thumbnail urls in the ArrayList.
The same logic is not working for video thumbnails. Of course that is a different question :)
Regards,
Sha.
try this one
final String[] pictureImageTemp= { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, pictureImageTemp, null,
null, MediaStore.Images.Media._ID);

How to get imagepath from thumbnail path of a image?

I am trying to get imagepath based on thumbail path , i have already tried solution from
android-getting-path-to-image-from-thumbnail, but it is based on gridview position, i am only retrieving specific images. Also i found one sample code from SO, the code is
private String getImagePathFromThumbPath(String thumbPath)
{
String imgPath=null;
// String[] projection = new String[] {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.IMAGE_ID};
String[] imagesDataPath={ MediaStore.Images.Media.DATA ,MediaStore.Images.Media._ID};
//mResolver.query() requires android API 16
Cursor thumbnails = mResolver.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, imagesDataPath,MediaStore.Images.Thumbnails.DATA+"=?",new String[]{thumbPath}, null, null);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor imageCursor = mResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, MediaStore.Images.Media._ID + "=?", new String[] {thumbId}, null);
if (imageCursor != null && imageCursor.moveToFirst()) {
// Your file-path will be here
imgPath= imageCursor.getString(imageCursor.getColumnIndex(filePathColumn[0]));
}
return imgPath;
}
The above method is bit modified to suit my needs and it returns nothing on Toasting, please tell how to retrieve imagepath using thumbnail path?
After a long time and relentless try, the solution is here
1. You need to find the image id which is image unique id from images table in thumbnail table, query to thumbnail provider (MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI) if you do not understand it, refer here , specifically IMAGE_ID,
Step 1 is to get retrievedImageId.
retrievedImageId = Long.parseLong(cursor.getString(imageIdInImages));
2. Now using the retrievedImageId get the image path, by again querying the content provider, only this time query the Images media provider (MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
String getImagePathFromThumbPath(String thumbPath)
{
String imagePath = null;
if(thumbPath != null )
{
String[] columns_to_return = {MediaStore.Images.Thumbnails.IMAGE_ID};
String where = MediaStore.Images.Thumbnails.DATA+" LIKE ?";
long retrievedImageId = -1;
String valuesAre[] = {"%"+thumbPath};
Cursor cursor = getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, columns_to_return, where, valuesAre, null);
if(cursor != null)
{
int imageIdInImages = cursor.getColumnIndex(MediaStore.Images.Thumbnails.IMAGE_ID);
for (cursor.moveToFirst();!cursor.isAfterLast(); cursor.moveToNext())
{
//STEP 1 to retrieve image ID
retrievedImageId = Long.parseLong(cursor.getString(imageIdInImages));
}
if(retrievedImageId != -1)
{
// STEP 2 Now
Log.i(TAG, "imageId-" + retrievedImageId);
String[] columnsReturn = {MediaStore.Images.Media.DATA};
String whereimageId = MediaStore.Images.Media._ID+" LIKE ?";
String valuesIs[] = {"%" + retrievedImageId};
Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columnsReturn, whereimageId, valuesIs, null);
int rawDataPath= mCursor.getColumnIndex(MediaStore.Images.Media.DATA);
for (mCursor.moveToFirst();!mCursor.isAfterLast(); mCursor.moveToNext())
{
imagePath = mCursor.getString(rawDataPath);
}
}
}
}
return imagePath;
}
If you still have doubt or error/exception, leave comment!

How to get last taken picture Uri [duplicate]

hey I want to get the last picture captured by user through any camera application.
I have no idea how to do that
can any one help me?
further I want to send that image as an attachment to an email or MMS..
thanks
// Find the last picture
String[] projection = new String[]{
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.MIME_TYPE
};
final Cursor cursor = getContext().getContentResolver()
.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null,
null, MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC");
// Put it in the image view
if (cursor.moveToFirst()) {
final ImageView imageView = (ImageView) findViewById(R.id.pictureView);
String imageLocation = cursor.getString(1);
File imageFile = new File(imageLocation);
if (imageFile.exists()) { // TODO: is there a better way to do this?
Bitmap bm = BitmapFactory.decodeFile(imageLocation);
imageView.setImageBitmap(bm);
}
}
I'm still working on the MMS sending part.
Inspired by https://stackoverflow.com/a/20065920/763459
So the main concern in that answer was not all the devices are using "DCIM" as the camera folder. Then I found out that if a file is located inside a app-specified folder, it will be indexed by ContentResolver but the other app doesn't have access to it, which means canRead=false. So here I come up with another solution:
while (cursor.moveToNext()) {
String imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
File imageFile = new File(imagePath);
if (imageFile.canRead() && imageFile.exists()) {
// we have found the latest picture in the public folder, do whatever you want
break;
}
}
Here it is in Kotlin. I have used Glide library to load the last image into an imageview
private fun getLastImageFromGallery(){
val uriExternal: Uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
val projection = arrayOf(
MediaStore.Images.ImageColumns._ID,
MediaStore.Images.Media._ID,
MediaStore.Images.ImageColumns.DATE_ADDED,
MediaStore.Images.ImageColumns.MIME_TYPE
)
val cursor: Cursor = applicationContext.contentResolver.query(uriExternal, projection, null,
null, MediaStore.Images.ImageColumns.DATE_ADDED + " DESC"
)!!
Log.i("Cursor Last", cursor.moveToLast().toString())
if (cursor.moveToFirst()) {
val columnIndexID = cursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
val imageId: Long = cursor.getLong(columnIndexID)
val imageURI = Uri.withAppendedPath(uriExternal, "" + imageId)
Glide.with(applicationContext)
.load(imageURI)
.transform(CenterCrop(), RoundedCorners(12))
.into(imageView)
}
cursor.close()
}

Loading contact picture via LOOKUP_KEY and openContactPhotoInputStream convenience method

I'm modifying my app to store information on contacts using LOOKUP_KEY instead of _ID as suggested by the API docs. The only problem I'm having is that I'm no longer able to load the contact's photo.
The problematic code is this one:
InputStream s = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), contactUri);
This is returning the following error: java.lang.IllegalArgumentException: URI: content://com.android.contacts/contacts/lookup/1424i118.2312i1220228108/photo
The contactUri that I am using as argument is acquired by the following: Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, contact_key);
and in this example, contact_key is 1424i118.2312i1220228108
Based on the API docs, this helper method should work with both CONTENT_URI or CONTENT_LOOKUP_URI, which I am using.
Any ideas? Thanks.
For anyone with a similar problem, this did the trick for me:
public Bitmap getPhoto(Uri uri){
Bitmap photoBitmap = null;
String[] projection = new String[] { ContactsContract.Contacts.PHOTO_ID };
Cursor cc = getContentResolver().query(uri, projection, null, null, null);
if(cc.moveToFirst()) {
final String photoId = cc.getString(cc.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
if(photoId != null) {
final Cursor photo = managedQuery(
Data.CONTENT_URI,
new String[] {Photo.PHOTO},
Data._ID + "=?",
new String[] {photoId},
null
);
// Convert photo blob to a bitmap
if(photo.moveToFirst()) {
byte[] photoBlob = photo.getBlob(photo.getColumnIndex(Photo.PHOTO));
photoBitmap = BitmapFactory.decodeByteArray(photoBlob, 0, photoBlob.length);
}
photo.close();
}
}
cc.close();
return photoBitmap;
}

Categories

Resources