Skip to content

Instantly share code, notes, and snippets.

@imandaliya
Last active October 20, 2021 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imandaliya/aa081441d11a8b1bedb702c58fbbe7d6 to your computer and use it in GitHub Desktop.
Save imandaliya/aa081441d11a8b1bedb702c58fbbe7d6 to your computer and use it in GitHub Desktop.
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