Skip to content

Instantly share code, notes, and snippets.

@avirias
Last active November 18, 2021 16:20
Show Gist options
  • Save avirias/b3d4ed010b6b154162280c4b709246d9 to your computer and use it in GitHub Desktop.
Save avirias/b3d4ed010b6b154162280c4b709246d9 to your computer and use it in GitHub Desktop.
suspend fun thumbnailExtract(videoFile: File): Bitmap {
return suspendCancellableCoroutine<Bitmap> {
try {
val retriever = MediaMetadataRetriever().apply {
setDataSource(videoFile.absolutePath)
}
val width =
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)
?.toInt()
?: throw Exception("width was null")
val height =
retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)
?.toInt()
?: throw Exception("height was null")
val cancellationSignal = CancellationSignal()
val bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ThumbnailUtils.createVideoThumbnail(
videoFile,
Size(width, height),
cancellationSignal
)
} else ThumbnailUtils.createVideoThumbnail(
videoFile.absolutePath,
MediaStore.Images.Thumbnails.MINI_KIND
)
it.resume(bitmap!!)
it.invokeOnCancellation {
cancellationSignal.cancel()
}
} catch (e: Exception) {
it.resumeWithException(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment