如何在 Android 中检测给定图像文件是否是动画 GIF

Add*_*dev 5 java animation android image gif

正在编写一个图像编辑器。

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

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

我检查了问题了解 gif 在 JAVA 中是否是动画的,但它不适用于 Android,因为 ImageIO 类不可用。

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

小智 5

下面的代码对我有用:

使用图像 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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();
}
Run Code Online (Sandbox Code Playgroud)