Created
June 27, 2020 18:37
-
-
Save morenodoug/83638b27d8030f74e55a90329d572f11 to your computer and use it in GitHub Desktop.
Adding an image to mediaStore(see in phone gallery) on Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void notifyMediaStoreScanner(Context mContext, Uri cacheImageUri) throws IOException { | |
Uri newImageUri = createImageInMediaStore(mContext, cacheImageUri); | |
ContentResolver resolver = mContext | |
.getContentResolver(); | |
FileInputStream input ; | |
FileOutputStream outputStream ; | |
try (ParcelFileDescriptor pfd = resolver | |
.openFileDescriptor(newImageUri, "w", null)) { | |
// Write data into the pending image. | |
try(ParcelFileDescriptor pfdInput = resolver.openFileDescriptor(cacheImageUri , "r",null)){ | |
outputStream =new FileOutputStream(pfd.getFileDescriptor()); | |
input = new FileInputStream(pfdInput.getFileDescriptor()); | |
int readResponse; | |
do { | |
byte[] bytes = new byte[1024]; | |
readResponse = input.read(bytes); | |
outputStream.write(bytes); | |
}while (readResponse !=-1); | |
input.close(); | |
outputStream.close(); | |
} catch (IOException e) { | |
Log.e(TAG, e.getMessage()); | |
throw new IOException("Error saving image "); | |
} | |
} catch (IOException e) { | |
Log.e(TAG, e.getMessage()); | |
throw new IOException("Error saving image "); | |
} | |
} | |
private static Uri createImageInMediaStore(Context mContext, Uri cacheImageUri){ | |
if (mContext== null) | |
throw new IllegalArgumentException("mContext can not be null"); | |
if(cacheImageUri == null) | |
throw new IllegalArgumentException("cacheImageUri can not be null"); | |
String imageName = cacheImageUri.getLastPathSegment(); | |
ContentResolver contentResolver = mContext.getContentResolver(); | |
Uri imagesCollection; | |
if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.P){ | |
imagesCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL); | |
}else{ | |
imagesCollection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY); | |
} | |
ContentValues newImageContentValues = new ContentValues(); | |
newImageContentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, imageName); | |
return contentResolver.insert(imagesCollection, newImageContentValues); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment