Created
April 17, 2021 08:57
-
-
Save binarynoise/a51714997a6d83318b4d79a386a44526 to your computer and use it in GitHub Desktop.
This file contains 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
@Throws(IllegalStateException::class) | |
private fun saveImageToDisk(bitmap: Bitmap) { | |
val fileName = "..." | |
if (Build.VERSION.SDK_INT < 29) { | |
val canWriteStorage = | |
Build.VERSION.SDK_INT < 23 || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED | |
check(canWriteStorage) { "no storage permission" } | |
val directory = pictureFolder | |
checkNotNull(directory) { "no storage permission" } | |
if (!directory.exists()) { | |
directory.mkdirs() | |
} | |
check(directory.exists()) { "folder could not be_created" } | |
check(directory.canWrite()) { "dir $directory exists but is not writable" } | |
val file = File(directory, fileName) | |
FileOutputStream(file).use { outputStream -> | |
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) | |
} | |
addToGallery(file) | |
} else { | |
val contentValues = ContentValues() | |
with(contentValues) { | |
put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES) // here you can add ' + "/" + subfolderName' to put the picture into a subfolder | |
put(MediaStore.Images.Media.DISPLAY_NAME, fileName) | |
put(MediaStore.Images.Media.MIME_TYPE, "image/png") | |
} | |
val imageUri: Uri? = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues) | |
checkNotNull(imageUri) { "Could not get an uri for $contentValues" } | |
val outputStream = contentResolver.openOutputStream(imageUri) | |
checkNotNull(outputStream) { "Could not get an OutputStream for uri $imageUri" } | |
outputStream.use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) } | |
} | |
} | |
@SuppressLint("SdCardPath") | |
@Suppress("DEPRECATION") // | |
private val pictureFolder: File? = run { | |
arrayOf( | |
Environment.getExternalStorageDirectory(), | |
File("/storage/emulated/$userNum/"), | |
File("/storage/emulated/legacy/"), | |
File("/data/media/$userNum"), | |
File("/sdcard/") | |
) | |
.asSequence() | |
.flatMap { f -> listOf(f.canonicalPath, f.absolutePath) } | |
.firstOrNull { File(it).canWrite() } | |
?.let { File(it, Environment.DIRECTORY_PICTURES) } // here you can add ' + "/" + subfolderName' to put the picture into a subfolder | |
} | |
private val userNum: Int = Process.myUid() / 100000 | |
fun addToGallery(path: String) { | |
MediaScannerConnection.scanFile(this, arrayOf(path), null, null) | |
} | |
fun addToGallery(file: File) { | |
addToGallery(file.absolutePath) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment