Last active
March 6, 2021 13:08
-
-
Save abircse/43c2733930bc974f7f01df3e5411f0bc to your computer and use it in GitHub Desktop.
SaveImageViewImageToGallery
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
fun saveImageToGallery(context: Context, fileName: String, photoView: PhotoView) { | |
val bitmapDrawable = photoView.drawable as BitmapDrawable | |
val bitmap = bitmapDrawable.bitmap | |
val filename = String.format("%s.png", fileName) | |
if (Build.VERSION.SDK_INT >= 29) { | |
val values = contentValues(filename) | |
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/" + "YOUR_FOLDER_NAME") | |
values.put(MediaStore.Images.Media.IS_PENDING, true) | |
// RELATIVE_PATH and IS_PENDING are introduced in API 29. | |
val uri: Uri? = context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) | |
if (uri != null) { | |
saveImageToStream(bitmap, context.contentResolver.openOutputStream(uri), context, fileName) | |
values.put(MediaStore.Images.Media.IS_PENDING, false) | |
context.contentResolver.update(uri, values, null, null) | |
} | |
} else { | |
val directory = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "USACE") | |
// getExternalStorageDirectory is deprecated in API 29 | |
if (!directory.exists()) { | |
directory.mkdirs() | |
} | |
val file = File(directory, filename) | |
saveImageToStream(bitmap, FileOutputStream(file), context, fileName) | |
if (file.absolutePath != null) { | |
val values = contentValues(filename) | |
values.put(MediaStore.Images.Media.DATA, file.absolutePath) | |
// .DATA is deprecated in API 29 | |
context.contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) | |
} | |
} | |
} | |
// When save done this method will call | |
private fun saveImageToStream(bitmap: Bitmap, outputStream: OutputStream?, context: Context, fileName: String) { | |
if (outputStream != null) { | |
try { | |
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) | |
outputStream.close() | |
showToast(context, "Saved File to your folder") | |
} catch (e: Exception) { | |
e.printStackTrace() | |
} | |
} | |
} | |
#Dont forget to get run time permission & menifest permission included in below- | |
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> | |
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment