Reputation: 119
I am using the MediaStore and ContentResolver API to save image files (jpg/png/gif) using MediaStore.Images
.
It works, but the problem is that all the files are saved with the .jpg extension and the file name is always "the current time in millis.jpg".
Here is an example of what I put in the ContentValues:
date_added=1575480356 _display_name=2067623.gif date_modified=1575480356 mime_type=image/gif
But after inserting it to the ContentResolver and writing the file, the display name changes to 2067623.jpg
and the file name to 1575480356.jpg
.
How do I get it to keep the file name and extension?
Code:
ContentResolver resolver = activity.getContentResolver();
Uri mediaCollection;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mediaCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
} else {
mediaCollection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues mediaDetails = new ContentValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
final String relativeLocation = Environment.DIRECTORY_PICTURES + File.separator + "my_folder";
mediaDetails.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
mediaDetails.put(MediaStore.Images.Media.IS_PENDING, 1);
mediaDetails.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);
}
String mimeType = "image" + "/" + getExtension(p); // jpg/png/gif
mediaDetails.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
mediaDetails.put(MediaStore.Images.Media.MIME_TYPE, mimeType);
mediaDetails.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis() / 1000);
mediaDetails.put(MediaStore.Images.Media.DATE_MODIFIED, System.currentTimeMillis() / 1000);
Uri contentUri = resolver.insert(mediaCollection, mediaDetails);
write(contentUri, resolver, p, fileName); // Write the file content using resolver.openOutputStream(contentUri)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
mediaDetails.clear();
mediaDetails.put(MediaStore.Images.Media.IS_PENDING, 0);
resolver.update(contentUri, mediaDetails, null, null);
}
Upvotes: 8
Views: 1441
Reputation: 320
Did you find a soution? I did not, so I end up doing this:
private void addImageToGalleryLegacy(@NonNull final String imagePath, @NonNull final String fileName) throws IOException {
File fIn = new File(imagePath);
String outPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File fOut = new File(outPath, fileName);
FileInputStream in = new FileInputStream(fIn);
FileOutputStream out = new FileOutputStream(fOut);
copy(in, out);
}
Basically (as we are in pre Q) we can copy the image straight to the gallery. "imagePath" is "Android/data/[package name]/files/Pictures" in my case.
Upvotes: -2