How to detect if a given image file is an animated GIF in Android

Viewed 4207

'm writing an image editor.

I do not support editing animated gifs, so when the user selects an image I need to show an error message if that image is an animated gif.

So given a file path, how can I distinguish between a static and an animated gif?

I checked the question Understand an gif is animated or not in JAVA but it does not apply for Android since the ImageIO class is not available.

Note: I only need to know if is animated, so I'd like the fastest approach

2 Answers

Summarize answers.. in Kotlin

private fun checkIfGif(file: File) : Boolean {
    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val source = ImageDecoder.createSource(file)
            val drawable = ImageDecoder.decodeDrawable(source)
            if (drawable is AnimatedImageDrawable) {
                return true
            }
        } else {
            val movie = Movie.decodeStream(file.inputStream())
            return movie != null
        }
    } catch (e: Throwable) {
        // not handled
    }
    return false
}
Related