Addev
Addev

Reputation: 32263

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

'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

Upvotes: 5

Views: 5068

Answers (2)

Brownsoo Han
Brownsoo Han

Reputation: 4711

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
}

Upvotes: 3

Jeffy Lee
Jeffy Lee

Reputation: 87

The code below works for me:

Check by using the image 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;
}

Or check by select file from gallery:

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();
}

Upvotes: 5

Related Questions