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

标签 java android image animation gif

正在编写图像编辑器。

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

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

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

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

最佳答案

下面的代码对我有用:

使用图片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();
}

关于java - 如何检测给定的图像文件是否是 Android 中的动画 GIF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36060976/

相关文章:

java - Java 获取网页加载的大概时间

java - 在字符串中查找整数java

java - 加载较小版本的图像以提高 Android 性能

android - Android中不同线程的数据库访问

objective-c - 使用 QTCaptureView 拍照

java - 如何使用maven构建一个jar,忽略测试结果?

java - Netty 线程模型在客户端连接多的情况下如何工作?

Android Studio Google-play-services 库

java - 如何强制 ImageIcon 具有特定大小?

python - 如何对绿地/草地中的白线进行图像分割