I’m trying to use MediaStore API
to save an image but it always save the file with this name
1637955326427.jpg and the size of the file is 0 B.
this is the code that i use:
OutputStream fos;
ContentResolver resolver = getBaseContext().getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, "fileName.jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
try {
fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),list.get(0).getDocfile().getUri());
if(bitmap!=null){
bitmap.compress(Bitmap.CompressFormat.JPEG,100,fos);
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
list.get(0).getDocFile()
return a DocumentFile
also i tested this on API 28
Thanks in advance
NOTICE this image already exist on the External Storage
, just need to copy it.
EDIT: I delete this code fos = resolver.openOutputStream(imageUri);
was duplucate. I do realy apologize. the file work fine but steal wrong name.
2
Answers
I delete this code
fos = resolver.openOutputStream(imageUri);
was duplicate. the image work fine but steal wrong name.About the Wrong name and extension, i think that
MediaStore
doesn't work fine with Android 9 and lower, because i tested the same code on Android 11 and it's working fineFirst lets take a look at getting write permissions for an existing image. Please note that the photopath does not necessarily exist yet but should point to the location you want your file to be saved.
This will form an overwrite request with the default camera
This will persist the permission to overwrite or create a new picture via the camera intent
Then in your activity:
This will take a picture if the permission request is accepted
To Take a picture using the default intent with a provider:
Declare your provider in the manifest
1.5: xml File paths file:
The above will give you permission to save to the documents folder. Replace as required.
Utilize the provider to take the picture
}
EDIT:
I forgot something
EDIT: Update by the name (in onActivityResult after requesting an overwrite permission)