Last active
October 20, 2021 07:43
-
-
Save imandaliya/aa081441d11a8b1bedb702c58fbbe7d6 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
fun Uri.calculateFileSizeInMB(context: Context): String? { | |
val cursor: Cursor? = context.contentResolver.query(this, null, null, null, null) | |
if (cursor != null) { | |
cursor.moveToFirst() | |
val sizeIndex: Int = cursor.getColumnIndex(OpenableColumns.SIZE) | |
val imageSize: Float = cursor.getLong(sizeIndex).toFloat() | |
cursor.close() | |
if (imageSize < 1024) { | |
context.contentResolver.openInputStream(this)?.let { | |
return it.readBytes().size.convertToReadableLength() | |
} | |
return null | |
} | |
return imageSize.convertToReadableLength() | |
} | |
return null | |
} | |
fun Float.convertToReadableLength(): String { | |
val fileSizeInKB = this / 1024f | |
val fileSizeInMB = fileSizeInKB / 1024f | |
return if (fileSizeInMB > 1) | |
String.format("%.2f MB", fileSizeInMB) | |
else | |
String.format("%.2f KB", fileSizeInKB) | |
} | |
fun Int.convertToReadableLength(): String { | |
return this.toFloat().convertToReadableLength() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment