Android Kotlin-检查图库中的图像是否为动画GIF

Android Kotlin-检查图库中的图像是否为动画GIF,android,kotlin,Android,Kotlin,这就是我尝试过的: try { val file = File(selectedPhotoUri!!.path) //val file = File(selectedPhotoUri.toString()) // this isn't working too val fileInputStream = FileInputStream(file) val outStream = ByteArrayOutputStream() val buffer = By

这就是我尝试过的:

try {

    val file = File(selectedPhotoUri!!.path)
    //val file = File(selectedPhotoUri.toString()) // this isn't working too
    val fileInputStream = FileInputStream(file)
    val outStream = ByteArrayOutputStream()
    val buffer = ByteArray(1024)
    var len = 0
    while (fileInputStream.read(buffer).also { len = it } != -1) {
        outStream.write(buffer, 0, len)
    }
    fileInputStream.close()
    val bytes = outStream.toByteArray()
    val gif = Movie.decodeByteArray(bytes, 0, bytes.size)
    //If the result is true, its a animated GIF
    if (gif != null) {
        Log.d(tagg, "is gif")
    } else {
        Log.d(tagg, "is not gif")
    }
} catch (ie: IOException) {
    ie.printStackTrace()
}

我没有得到任何结果,
Movie.decodeByteArray
已被弃用,看起来我需要使用
AnimatedImageDrawable
,但如何使用?

使用
ImageDecoder
类,它将识别要解码的所提供图像源的类型,对于静态图像,它将创建
BitmapDrawable
,对于动画图像-
AnimatedImageDrawable

val source = ImageDecoder.createSource(assets, assetFileName)
val drawable = ImageDecoder.decodeDrawable(source)

imageView.setImageDrawable(drawable)

if (drawable is AnimatedImageDrawable) {

  // it is a GIF, and you can play the animation by calling drawable.start()

} else {

  // it is not a GIF

}

您可以通过URL后缀进行检查。如果没有解决方案来检查它是否为真正的GIF:D,那么我们将这样做,因为用户可以重命名文件扩展名。如果API<27,您可以使用
Movie.decodeByteArray
,实现另一组条件,这在API 28中已被弃用