【问题标题】:How to detect if a given image file is an animated GIF in Android如何检测给定的图像文件是否是Android中的动画GIF
【发布时间】:2016-07-03 19:49:45
【问题描述】:

正在编写图像编辑器。

我不支持编辑动画 gif,因此当用户选择图像时,如果该图像是动画 gif,我需要显示错误消息。

那么给定一个文件路径,如何区分静态 gif 和动画 gif?

我检查了Understand an gif is animated or not in JAVA 的问题,但它不适用于 Android,因为 ImageIO 类不可用。

注意:我只需要知道是否是动画,所以我想要最快的方法

【问题讨论】:

标签: java android image animation gif


【解决方案1】:

下面的代码对我有用:

使用图片http url检查。

URL url = new URL(path);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();

byte[] buffer = new byte[1024];
int len = 0;

while ((len = inputStream.read(buffer)) != -1) {
    outStream.write(buffer, 0, len);
}

inputStream.close();
byte[] bytes = outStream.toByteArray();

Movie gif = Movie.decodeByteArray(bytes, 0, bytes.length);
//If the result is true, its a animated GIF
if (gif != null) {
    return true;
} else {
    return false;
}

或通过从图库中选择文件进行检查:

try {
    //filePath is a String converted from a selected image's URI
    File file = new File(filePath);
    FileInputStream fileInputStream = new FileInputStream(file);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    byte[] buffer = new byte[1024];
    int len = 0;

    while ((len = fileInputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, len);
    }

    fileInputStream.close();
    byte[] bytes = outStream.toByteArray();

    Movie gif = Movie.decodeByteArray(bytes, 0, bytes.length);
    //If the result is true, its a animated GIF
    if (gif != null) {
        type = "Animated";
        Log.d("Test", "Animated: " + type);
    } else {
        type = "notAnimated";
        Log.d("Test", "Animated: " + type);
   }
} catch (IOException ie) {
   ie.printStackTrace();
}

【讨论】:

【解决方案2】:

总结答案.. 在 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
}

【讨论】:

    猜你喜欢
    • 2015-02-08
    • 2023-04-05
    • 2022-09-30
    • 2014-02-03
    • 2010-11-27
    • 2011-03-28
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多