264
votes

I want to display animated GIF images in my aplication. As I found out the hard way Android doesn't support animated GIF natively.

However it can display animations using AnimationDrawable:

Develop > Guides > Images & Graphics > Drawables Overview

The example uses animation saved as frames in application resources but what I need is to display animated gif directly.

My plan is to break animated GIF to frames and add each frame as drawable to AnimationDrawable.

Does anyone know how to extract frames from animated GIF and convert each of them into Drawable?

30
Do you mean within android , or extracting frames from a gif with an external tool?Osmund
it definitely is a bug, see IssueTracker for more information.fbtb
Just for all those who came here by searching for an app that can display animated GIFs: quickPicrubo77
Use fresco to display GIF github.com/facebook/fresco I think this is a simple solution.kaitian521

30 Answers

191
votes

Android actually can decode and display animated GIFs, using android.graphics.Movie class.

This is not too much documented, but is in SDK Reference. Moreover, it is used in Samples in ApiDemos in BitmapDecode example with some animated flag.

68
votes

UPDATE:

Use glide:

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.0.0'
}

usage:

Glide.with(context).load(GIF_URI).into(new GlideDrawableImageViewTarget(IMAGE_VIEW));

see docs

27
votes

also put (main/assets/htmls/name.gif) [with this html adjust to the size]

<html style="margin: 0;">
<body style="margin: 0;">
<img src="name.gif" style="width: 100%; height: 100%" />
</body>
</html>

declare in your Xml for example like this (main/res/layout/name.xml): [you define the size, for example]

<WebView
android:layout_width="70dp"
android:layout_height="70dp"
android:id="@+id/webView"
android:layout_gravity="center_horizontal" />

in your Activity put the next code inside of onCreate

web = (WebView) findViewById(R.id.webView); 
web.setBackgroundColor(Color.TRANSPARENT); //for gif without background
web.loadUrl("file:///android_asset/htmls/name.html");

if you want load dynamically you have to load the webview with data:

// or "[path]/name.gif" (e.g: file:///android_asset/name.gif for resources in asset folder), and in loadDataWithBaseURL(), you don't need to set base URL, on the other hand, it's similar to loadData() method.
String gifName = "name.gif";
String yourData = "<html style=\"margin: 0;\">\n" +
        "    <body style=\"margin: 0;\">\n" +
        "    <img src=" + gifName + " style=\"width: 100%; height: 100%\" />\n" +
        "    </body>\n" +
        "    </html>";
// Important to add this attribute to webView to get resource from outside.
webView.getSettings().setAllowFileAccess(true);

// Notice: should use loadDataWithBaseURL. BaseUrl could be the base url such as the path to asset folder, or SDCard or any other path, where your images or the other media resides related to your html
webView.loadDataWithBaseURL("file:///android_asset/", yourData, "text/html", "utf-8", null);
// Or if you want to load image from SD card or where else, here is the idea.
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
webView.loadDataWithBaseURL(base + '/', yourData, "text/html", "utf-8", null);

suggestion: is better load gif with static images for more information check https://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html

That's it, I hope you help.

Currently we can use Glide https://github.com/bumptech/glide

21
votes

I solved the problem by splitting gif animations into frames before saving it to phone, so I would not have to deal with it in Android.

Then I download every frame onto phone, create Drawable from it and then create AnimationDrawable - very similar to example from my question

17
votes

i found a very easy way, with a nice and simple working example here

display animated widget

Before getting it working there are some chages to do do in the code

IN THE FOLLOWING

    @Override
    public void onCreate(Bundle savedInstanceState){    
        super.onCreate(savedInstanceStated);   
        setContentView(new MYGIFView());
    }    
}

just replace

setContentView(new MYGIFView());

in

setContentView(new MYGIFView(this));

AND IN

public GIFView(Context context) {
    super(context);

Provide your own gif animation file

    is = context.getResources().openRawResource(R.drawable.earth);
    movie = Movie.decodeStream(is);
}

REPLACE THE FIRST LINE IN

public MYGIFView(Context context) {

according to the name of the class...

after done this little changes it should work as for me...

hope this help

15
votes

Glide 4.6

1. To Load gif

GlideApp.with(context)
            .load(R.raw.gif) // or url
            .into(imageview);

2. To get the file object

GlideApp.with(context)
                .asGif()
                .load(R.raw.gif) //or url
                .into(new SimpleTarget<GifDrawable>() {
                    @Override
                    public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {

                        resource.start();
                      //resource.setLoopCount(1);
                        imageView.setImageDrawable(resource);
                    }
                });
10
votes

Ways to show animated GIF on Android:

  • Movie class. As mentioned above, it's fairly buggy.
  • WebView. It's very simple to use and usually works. But sometimes it starts to misbehave, and it's always on some obscure devices you don't have. Plus, you can’t use multiple instances in any kind of list views, because it does things to your memory. Still, you might consider it as a primary approach.
  • Custom code to decode gifs into bitmaps and show them as Drawable or ImageView. I'll mention two libraries:

https://github.com/koral--/android-gif-drawable - decoder is implemented in C, so it's very efficient.

https://code.google.com/p/giffiledecoder - decoder is implemented in Java, so it's easier to work with. Still reasonably efficient, even with large files.

You'll also find many libraries based on GifDecoder class. That's also a Java-based decoder, but it works by loading the entire file into memory, so it's only applicable to small files.

10
votes

I had a really hard time to have animated gif working in Android. I only had following two working:

  1. WebView
  2. Ion

WebView works OK and really easy, but the problem is it makes the view loads slower and the app would be unresponsive for a second or so. I did not like that. So I have tried different approaches (DID NOT WORK):

  1. ImageViewEx is deprecated!
  2. picasso did not load animated gif
  3. android-gif-drawable looks great, but it caused some wired NDK issues in my project. It caused my local NDK library stop working, and I was not able to fix it

I had some back and forth with Ion; Finally, I have it working, and it is really fast :-)

Ion.with(imgView)
  .error(R.drawable.default_image)
  .animateGif(AnimateGifMode.ANIMATE)
  .load("file:///android_asset/animated.gif");
9
votes

Glide

Image Loader Library for Android, recommended by Google.

  • Glide is quite similar to Picasso but this is much faster than Picasso.
  • Glide consumes less memory than Picasso.

What that Glide has but Picasso doesn't

An ability to load GIF Animation to a simple ImageView might be the most interesting feature of Glide. And yes, you can't do that with Picasso. enter image description here Some important links-

  1. https://github.com/bumptech/glide
  2. http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en
7
votes

Use ImageViewEx, a library that makes using a gif as easy as using an ImageView.

7
votes

Try this, bellow code display gif file in progressbar

loading_activity.xml(in Layout folder)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff" >

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:indeterminate="true"
        android:indeterminateDrawable="@drawable/custom_loading"
        android:visibility="gone" />

</RelativeLayout>

custom_loading.xml(in drawable folder)

here i put black_gif.gif(in drawable folder), you can put your own gif here

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/black_gif"
    android:pivotX="50%"
    android:pivotY="50%" />

LoadingActivity.java(in res folder)

public class LoadingActivity extends Activity {

    ProgressBar bar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        bar = (ProgressBar) findViewById(R.id.progressBar);
        bar.setVisibility(View.VISIBLE);

    }

}
7
votes

Nobody has mentioned the Ion or Glide library. they work very well.

It's easier to handle compared to a WebView.

5
votes

I have had success with the solution proposed within this article, a class called GifMovieView, which renders a View which can then be displayed or added to a specific ViewGroup. Check out the other methods presented in parts 2 and 3 of the specified article.

The only drawback to this method is that the antialiasing on the movie is not that good (must be a side-effect of using the "shady" Android Movie Class). You are then better off setting the background to a solid color within your animated GIF.

4
votes

Some thoughts on the BitmapDecode example... Basically it uses the ancient, but rather featureless Movie class from android.graphics. On recent API versions you need to turn off hardware acceleration, as described here. It was segfaulting for me otherwise.

<activity
            android:hardwareAccelerated="false"
            android:name="foo.GifActivity"
            android:label="The state of computer animation 2014">
</activity>

Here is the BitmapDecode example shortened with only the GIF part. You have to make your own Widget (View) and draw it by yourself. Not quite as powerful as an ImageView.

import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.*;
import android.view.View;

public class GifActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new GifView(this));
    }

    static class GifView extends View {
        Movie movie;

        GifView(Context context) {
            super(context);
            movie = Movie.decodeStream(
                    context.getResources().openRawResource(
                            R.drawable.some_gif));
        }
        @Override
        protected void onDraw(Canvas canvas) {   
            if (movie != null) {
                movie.setTime(
                    (int) SystemClock.uptimeMillis() % movie.duration());
                movie.draw(canvas, 0, 0);
                invalidate();
            }
        }
    }
}

2 other methods, one with ImageView another with WebView can be found in this fine tutorial. The ImageView method uses the Apache licensed android-gifview from Google Code.

4
votes

@PointerNull gave good solution, but it is not perfect. It doesn't work on some devices with big files and show buggy Gif animation with delta frames on pre ICS version. I found solution without this bugs. It is library with native decoding to drawable: koral's android-gif-drawable.

2
votes

Put it into a WebView, it has to be able to display it correctly, since the default browser supports gif files. (Froyo+, if i am not mistaken)

2
votes

There are two options to load animated gifs into our Android apps

1)Using Glide to load the gif into an ImageView.

    String urlGif = "https://cdn.dribbble.com/users/263558/screenshots/1337078/dvsd.gif";
    //add Glide implementation into the build.gradle file.
    ImageView imageView = (ImageView)findViewById(R.id.imageView);
    Uri uri = Uri.parse(urlGif);
    Glide.with(getApplicationContext()).load(uri).into(imageView);

2) Using an html to load the gif into a WebView

Create the html with the address to the .gif file:

<html style="margin: 0;">
<body style="margin: 0;">
<img src="https://..../myimage.gif" style="width: 100%; height: 100%" />
</body>
</html>

store this file into the assets directory:

enter image description here

The load this html into the WebView of your application:

    WebView webView =  (WebView)findViewById(R.id.webView);
    webView = (WebView) findViewById(R.id.webView);
    webView.loadUrl("file:///android_asset/html/webpage_gif.html");

Heres is a complete example of this two options.

enter image description here

2
votes

For only android API (Android Pie)28 and +

AnimatedImageDrawable
// ImageView from layout
val ima : ImageView = findViewById(R.id.img_gif)
// create AnimatedDrawable 
val decodedAnimation = ImageDecoder.decodeDrawable(
        // create ImageDecoder.Source object
        ImageDecoder.createSource(resources, R.drawable.tenor))
// set the drawble as image source of ImageView
ima.setImageDrawable(decodedAnimation)
// play the animation
(decodedAnimation as? AnimatedImageDrawable)?.start()

XML code, add a ImageView

<ImageView
    android:id="@+id/img_gif"
    android:background="@drawable/ic_launcher_background" <!--Default background-->
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_width="200dp"
    android:layout_height="200dp" />

AnimatedImageDrawable is a child of Drawable and created by ImageDecoder.decodeDrawable

ImageDecoder.decodeDrawable which further required the instance of ImageDecoder.Source created by ImageDecoder.createSource.

ImageDecoder.createSource can only take source as a name, ByteBuffer, File, resourceId, URI, ContentResolver to create source object and uses it to create AnimatedImageDrawable as Drawable (polymorphic call)

static ImageDecoder.Source  createSource(AssetManager assets, String fileName)
static ImageDecoder.Source  createSource(ByteBuffer buffer)
static ImageDecoder.Source  createSource(File file)
static ImageDecoder.Source  createSource(Resources res, int resId)
static ImageDecoder.Source  createSource(ContentResolver cr, Uri uri)

Note: You can also create Bitmap using ImageDecoder#decodeBitmap.

Output:

AnimatedDrawable also supports resizing, frame and color manipulation

1
votes

I think the better library to handle gif files is this one: by koral

Used it and i'm successful and this library is dedicated to GIF'S; but where as the picasso and glide are general purpose image framework; so i think the developers of this library have entirely concentrated on gif files

1
votes

Use fresco. Here's how to do it:

http://frescolib.org/docs/animations.html

Here's the repo with the sample:

https://github.com/facebook/fresco/tree/master/samples/animation

Beware fresco does not support wrap content!

1
votes

Just wanted to add that the Movie class is now deprecated.

This class was deprecated in API level P.

It is recommended to use this

AnimatedImageDrawable

Drawable for drawing animated images (like GIF).

0
votes

Similar to what @Leonti said, but with a little more depth:

What I did to solve the same problem was open up GIMP, hide all layers except for one, export it as its own image, and then hide that layer and unhide the next one, etc., until I had individual resource files for each one. Then I could use them as frames in the AnimationDrawable XML file.

0
votes

I solved this by spliting gif in frames and use standard android animation

0
votes

Something I did for showing gifs in apps. I extended ImageView so people can use its attributes freely. It can show gifs from url or from the assets directory. The library also makes it easy for extending classes to inherit from it and extend it to support different methods to initialize the gif.

https://github.com/Gavras/GIFView

There's a little guide on the github page.

It was also published on Android Arsenal:

https://android-arsenal.com/details/1/4947

Use example:

From XML:

<com.whygraphics.gifview.gif.GIFView xmlns:gif_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_activity_gif_vie"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:scaleType="center"
        gif_view:gif_src="url:http://pop.h-cdn.co/assets/16/33/480x264/gallery-1471381857-gif-season-2.gif" />

In the activity:

    GIFView mGifView = (GIFView) findViewById(R.id.main_activity_gif_vie);

    mGifView.setOnSettingGifListener(new GIFView.OnSettingGifListener() {
                @Override
                public void onSuccess(GIFView view, Exception e) {
                    Toast.makeText(MainActivity.this, "onSuccess()", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(GIFView view, Exception e) {

        }
});

Setting the gif programmatically:

mGifView.setGifResource("asset:gif1");
0
votes

Easiest way - Can be consider the below code

We can take advantage of Imageview setImageResource , refer below code for the same.

The below code can be used to show the image like gif incase if you have the multiple split image of gif. Just split the gif into individual png from a online tool and put image in the drawable like the below order

image_1.png, image_2.png, etc.

Have the handler to change the image dynamically.

int imagePosition = 1;
    Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            public void run() {
                updateImage();
            }
        };




    public void updateImage() {

                appInstance.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int resId = getResources().getIdentifier("image_" + imagePosition, "drawable", appInstance.getPackageName());
                        gifImageViewDummy.setImageResource(resId);
                        imagePosition++;
    //Consider you have 30 image for the anim
                        if (imagePosition == 30) {
//this make animation play only once
                            handler.removeCallbacks(runnable);

                        } else {
    //You can define your own time based on the animation
                            handler.postDelayed(runnable, 50);
                        }

//to make animation to continue use below code and remove above if else
// if (imagePosition == 30)
//imagePosition = 1;
// handler.postDelayed(runnable, 50);
// 
                    }
                });
              }
0
votes

The easy way to display animated GIF directly from URL to your app layout is to use WebView class.

Step 1: In your layout XML

<WebView
android:id="@+id/webView"
android:layout_width="50dp"
android:layout_height="50dp"
/>

Step 2: In your Activity

WebView wb;
wb = (WebView) findViewById(R.id.webView);
wb.loadUrl("https://.......);

Step 3: In your Manifest.XML make Internet permission

<uses-permission android:name="android.permission.INTERNET" />

Step 4: In case you want to make your GIF background transparent and make GIF fit to your Layout

wb.setBackgroundColor(Color.TRANSPARENT);
wb.getSettings().setLoadWithOverviewMode(true);
wb.getSettings().setUseWideViewPort(true);
0
votes

If you want to use Glide for loading gif:

Glide.with(this)
        .asGif()
        .load(R.raw.onboarding_layers) //Your gif resource
        .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
        .listener(new RequestListener<GifDrawable>() {
            @Override
            public boolean onLoadFailed(@Nullable @org.jetbrains.annotations.Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                return false;
            }

            @Override
            public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                resource.setLoopCount(1);
                return false;
            }
        })
        .into((ImageView) view.findViewById(R.id.layer_icons));
0
votes

To save resources there is glide library for. Have no idea why to use anything else, especialy webview to show image only. Glide is perfect and easy library that prepares animated drawable from gif and put it directly to imageview. The logic of gifdrawable handle animation itself. Gif have lzw ziped raw rgb data of an animation inside. There is no reason for complicated usage of webview and manage more files to show just a gif file in app.

-1
votes

You may use GifAnimationDrawable library found in this link - https://github.com/Hipmob/gifanimateddrawable, and which convert any gif to AnimationDrawable. Enjoy :)

-2
votes

First of all the Android browser should support Animated GIFs. If it doesn't then it's a bug! Have a look at the issue trackers.

If you're displaying these animated GIFs outside of a browser it might be a different story. To do what you're asking would require external library that supports the decoding of Animated GIFs.

The first port of call would be to look at Java2D or JAI (Java Advanced Imaging) API, although I would be very surprised if Android Dalvik would support those libraries in your App.