Last active
November 18, 2021 16:20
-
-
Save avirias/b3d4ed010b6b154162280c4b709246d9 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
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