Kotlin Extension Solution
Here is the way to fetch media file dimensions in Kotlin
val (width, height) = myFile.getMediaDimensions(context)
fun File.getMediaDimensions(context: Context): Pair<Int, Int>? {
if (!exists()) return null
val retriever = MediaMetadataRetriever()
retriever.setDataSource(context, Uri.parse(absolutePath))
val width = retriever.extractMetadata(METADATA_KEY_VIDEO_WIDTH).toIntOrNull() ?: return null
val height = retriever.extractMetadata(METADATA_KEY_VIDEO_HEIGHT).toIntOrNull() ?: return null
retriever.release()
return Pair(width, height)
}
If you want to make it safer (Uri.parse could throw exception), use this combination. The others are generally just useful as well :)
fun String?.asUri(): Uri? {
try {
return Uri.parse(this)
} catch (e: Exception) {
}
return null
}
val File.uri get() = absolutePath.asUri()
fun File.getMediaDimensions(context: Context): Pair<Int, Int>? {
if (!exists()) return 0
val retriever = MediaMetadataRetriever()
retriever.setDataSource(context, uri)
val width = retriever.extractMetadata(METADATA_KEY_VIDEO_WIDTH).toIntOrNull() ?: return null
val height = retriever.extractMetadata(METADATA_KEY_VIDEO_HEIGHT).toIntOrNull() ?: return null
retriever.release()
return Pair(width, height)
}
Not necessary here, but generally helpful additional Uri extensions
val Uri?.exists get() = if (this == null) false else asFile().exists()
fun Uri.asFile(): File = File(toString())