Hot questions for Using Glide in gif

Question:

What I have is this:

Glide
            .with(this)
            .load(imageUrl)
            .asGif()
            .diskCacheStrategy(DiskCacheStrategy.SOURCE)
            .placeholder(R.drawable.gif)
            .into(imageView);

But instead, I want to use Glide to load the same gif asBitmap() to use as placeholder for while it's loading the actual gif.

Like if I could do: .placeholder(Glide.with(this).load(imageUrl).asBitmap())


Answer:

You have to pass the URL in .thumbnail(url) as

.thumbnail(Glide
        .with(context)
        .load(Url)
        .asBitmap()

Or like this:-

DrawableRequestBuilder<String> thumbnail = Glide.with(context)
            .diskCacheStrategy(DiskCacheStrategy.ALL)
            .load(url);
    try {
        Glide.with(context)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .error(placeholder)
                .load(url)
                .thumbnail(thumbnail)
                .into(imageView);
    } catch (Exception e) {
        e.printStackTrace();
    }

Reference:

https://github.com/bumptech/glide/issues/1198

https://futurestud.io/tutorials/glide-thumbnails

https://github.com/bumptech/glide/issues/362

private void loadImage(ImageView image, @RawRes int typeID, String imagePath) {
Context context = image.getContext();
BitmapPool pool = Glide.get(context).getBitmapPool();

// OPTION 1 Bitmap
Glide
    .with(image.getContext())
    .load(imagePath)
    .asBitmap()
    .animate(android.R.anim.fade_in)
    .placeholder(R.drawable.image_loading)
    .error(R.drawable.image_error)
    .thumbnail(Glide
        .with(context)
        .load(typeID)
        .asBitmap()
        .imageDecoder(new SvgBitmapDecoder(pool)) // implements ResourceDecoder<InputStream, Bitmap>
    )
    .into(image)
;

// OPTION 2 GlideDrawable
Glide
    .with(image.getContext())
    .load(imagePath)
    .crossFade()
    .placeholder(R.drawable.image_loading)
    .error(R.drawable.image_error)
    .thumbnail(Glide
        .with(context)
        .load(typeID)
        .decoder(new GifBitmapWrapperResourceDecoder(
                    new ImageVideoBitmapDecoder(
                        new SvgBitmapDecoder(pool),
                        null /*fileDescriptorDecoder*/
                    ),
                    // just to satisfy GifBitmapWrapperResourceDecoder.getId() which throws NPE otherwise
                    new GifResourceDecoder(context, pool),
                    pool
                )
        )
    )
    .into(image)
;
}

Question:

I want to load a gif image from my raw resources( or my device storage), and also scale it to desired width and height with Glide. I successfully in loading gif image but can't scaled it down.

Here is my loading code:

Glide.with(getContext()).load(R.raw.abc).override(
                getResources().getDimensionPixelSize(R.dimen.note_icon_width),
                getResources().getDimensionPixelSize(R.dimen.note_icon_height)).into(this);

And here is the declaration view in my xml:

<ImageView
        android:id="@+id/btn_open_warning"
        android:layout_width="48dp"
        android:layout_height="match_parent"
        android:src="@drawable/ic_whatnew_toolbox"
        app:srcSecondState="@drawable/ic_note_menu_disable" />

Answer:

I'm not familiar with Glide but maybe if you override onResourceReady() method you can scale it down.

Use a .listener() as follows

Glide.with(getContext())
                .load(R.raw.abc)
                .listener(new RequestListener<Uri, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, Uri model, Target<GlideDrawable> target, boolean isFirstResource) {
                        //PENG
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, Uri model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        GlideDrawableImageViewTarget glideTarget = (GlideDrawableImageViewTarget) target;
                        ImageView iv = glideTarget.getView();
                        int width = iv.getMeasuredWidth();
                        int targetHeight = width * resource.getIntrinsicHeight() / resource.getIntrinsicWidth();
                        if(iv.getLayoutParams().height != targetHeight) {
                            iv.getLayoutParams().height = targetHeight;
                            iv.requestLayout();
                        }
                        return false;
                    }
                })
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(this);

Question:

Sidenote - although some of my examples are in Kotlin, answers in either Java or Kotlin are helpful.

I'm creating a GIF keyboard using the Commit Content API. To do this, I need to be able to create .gif files.

I'm using Glide to fetch the images from the internet and display them in a list inside of a recyclerview.

For each image Glide downloads, I have to create a File object with the data of that image.

I see two methods that could accomplish this objective.

1] Create a listener that overrides onResourceReady like so. The problem with this method is that I don't know how to convert a GifDrawable to a .gif file because all the Stack Overflow posts talk about how to convert a Drawable to a file:

    Glide.with(context)
            .asGif()
            .load(items[position])
            .listener(object : RequestListener<GifDrawable> {
                override fun onLoadFailed(e: GlideException?, model: Any?, target: Target<GifDrawable>?, isFirstResource: Boolean): Boolean {
                    Log.d("VED-APP","Glide Load Failed")
                    return false
                }

                override fun onResourceReady(resource: GifDrawable?, model: Any?, target: Target<GifDrawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
                    //I need code to convert the GifDrawable to a File

                    return false
                }

            })
            .into(holder.imageView)

2] Load the image to a ByteArray or something similar. Example Java code, taken from the post Glide - download and resize GIF into a file, could look like this. The problem with this code is that

A] .into(width,height) is deprecated

B] there is no .toBytes method

C] I don't want to specify the dimensions of my GIF - I'd just like to use the original size. (Or, at the very least, I'd like to preserve the aspect ratio)

byte[] bytes = Glide.with(context)
                    .load(items[position])
                    .asGif()
                    .toBytes()
                    .into(250, 250)
                    .get();
file = new File(fileName);

FileOutputStream fileWriter = new FileOutputStream(file);
fileWriter.write(bytes);
fileWriter.flush();
fileWriter.close();

Can someone help me improve either of these two methods, or suggest a new way to convert a GIF to a file with Glide?


Answer:

Update @Nhật Tôn's solution is probably better if you just need the URI for the content comit API.

I don't know if @Nhật Tôn's solution works. But, this is the solution I am using right now, which is based off of their solution. My solution is in Kotlin, but it can be easily converted to Java.

First, I load the image into the ImageView with the following code:

//items[position] is a string that represents a URL
Glide.with(context)
        .load(items[position])
        .into(holder.imageView)

Then I fetch the GifDrawable from the ImageView and write it to a File object.

val byteBuffer = (holder.imageView.drawable as GifDrawable).buffer
val gifFile = File(localDirectory, "test.gif")

val output = FileOutputStream(gifFile)
val bytes = ByteArray(byteBuffer.capacity())
(byteBuffer.duplicate().clear() as ByteBuffer).get(bytes)
output.write(bytes, 0 ,bytes.size)
output.close()

A potential problem with this solution is that the GifDrawable could be modified while it is being written to a file.

A fix to this is cloning the GifDrawable like so before writing it to a file:

val newGifDrawable = ((holder.imageView.drawable).constantState.newDrawable().mutate()) as GifDrawable

Question:

When I tried to load from a gif url to a ImageView, I added more condition by RequestListener, but It didn't work|

Glide version: 4.7.1 it worked when I coded: Glide.with(context).asGif().load(gifModel.url).into(ivGif);

I want after loading gif completely, ivPreGif GONE

I added more contition but I didn't work

Glide.with(context)
                                .asGif()
                                .load(gifModel.url)
                                .listener(new RequestListener<GifDrawable>() {
                                    @Override
                                    public boolean onLoadFailed(@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) {
                                        ivPreGif.setVisibility(View.GONE);
                                        ivGif.setVisibility(View.VISIBLE);
                                        return false;
                                    }
                                })
                                .into(ivGif);

Answer:

Try this..

load method give your gif url.

        Glide.with(this).load(R.drawable.user).into(imageView);

  Glide.with(this).load(R.drawable.user)
            .listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                     ivPreGif.setVisibility(View.GONE);
                    return false;
                }
            })
            .into(imageView);

Question:

I am currently using the Glide library to play GIFs as follows.

Glide.with(this).load(gifUrl).into(ImageView);

This works fine but I would like the user to have the option to rewind, pause and forward the GIF. I am thinking just buttons that rewind/forward 10 seconds and another button to pause. It won't be possible for me to use mp4 videos, and thus a video playing library, since the files that I am using are GIFs. Is there any way I can do this while still using Glide or will I have to use another library?

Any help is greatly appreciated.


Answer:

Your best bet is probably to convert your gif into an mp4 video using a third party library and then use native android functions to forward, pause, and rewind that mp4.

I'm sure there is an API that does this, you just need to look. Maybe try looking here https://android-arsenal.com/tag/193. It would be much harder to forward and rewind a gif, so you need to first convert.

An example of how to create your "forward 10 seconds" button. seekForwardTime would be 10,000 ms.

 btnForward.setOnLongClickListener(new OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            // get current song position
            int currentPosition = mp.getCurrentPosition();
            // check if seekForward time is lesser than song duration
            if (currentPosition + seekForwardTime <= mp.getDuration()) {
                // forward song
                mp.seekTo(currentPosition + seekForwardTime);
            } else {
                // forward to end position
                mp.seekTo(mp.getDuration());
            }
            return false;
        }
    });

Question:

I'm trying to find out end of gif with glide.

this is the code that I find on web:

Glide.with(thisActivity).asGif().load(R.raw.logo_gif_motion_low).listener(object : RequestListener<GifDrawable> {
                override fun onLoadFailed(p0: GlideException?, p1: Any?, p2: Target<GifDrawable>, p3: Boolean): Boolean {

                }
                override  fun onResourceReady(p0: GifDrawable?, p1: Any?, p2: Target<GifDrawable>, p3: DataSource?, p4: Boolean): Boolean {

                    return false
                }
            }).into(splashscreen);

the problem is , it doesn't accept GifDrawable in Target.

the error saying that:


Answer:

Use

target: com.bumptech.glide.request.target.Target<GifDrawable>?

instead of

Target<GifDrawable>

Try this

    Glide.with(this).asGif().load("").listener(object : RequestListener<GifDrawable> {
        override fun onResourceReady(resource: GifDrawable?, model: Any?, target: Target<GifDrawable>?, dataSource: DataSource?, isFirstResource: Boolean): Boolean {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }

        override fun onLoadFailed(e: GlideException?, model: Any?, target: com.bumptech.glide.request.target.Target<GifDrawable>?, isFirstResource: Boolean): Boolean {
            TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
        }


    }).into(splashscreen)

Question:

I tried to get this GIF from a URL like this:

 Glide.with(context)
                .load("http://artfcity.com/wp-content/uploads/2017/07/tumblr_osmx1ogeOD1r2geqjo1_540.gif")
                .into(new GlideDrawableImageViewTarget(imageViewBaby) {
                    @Override
                    public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                        super.onResourceReady(drawable, anim);
                        imageViewBaby.setImageDrawable(drawable);
                        imageViewBaby.invalidate();
                        imageViewBaby.requestLayout();
                    }
                });

But the GIF will not move or start. It's just like an image! How to solve this issue?


Answer:

Try this

Add dependency

  implementation 'com.github.bumptech.glide:glide:4.4.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.4.0'

Gif Loading

    Glide.with(this)
      .load("http://artfcity.com/wp-
      content/uploads/2017/07/tumblr_osmx1ogeOD1r2geqjo1_540.gif")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
            .into(imageView);

See this https://github.com/bumptech/glide/issues/2471

Question:

I want to show GIF using Glide in ImageView, and set this ImageView in AlertDialog.

ImageView gifImageView = new ImageView(context);
Glide.with(context).load(recorder.getPictureFile()).asGif().into(gifImageView);

AlertDialog.Builder share_dialog = new AlertDialog.Builder(context);
share_dialog.setMessage("Live Message Saved");
share_dialog.setPositiveButton("Done", null);
share_dialog.setView(gifImageView);
share_dialog.show(); 

But it only shows Message and PositiveButton.

I can't understand why, what should I do to fix it ?

Update:2017/09/23

I create another project to test this issue, here is the code.

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button_main = (Button)findViewById(R.id.button_main);
        imageView_main = (ImageView)findViewById(R.id.imageView_main);

        GlideDrawableImageViewTarget imageViewMainTarget = new GlideDrawableImageViewTarget(imageView_main);
        Glide.with(MainActivity.this).load(R.raw.test).into(imageViewMainTarget);

        button_main.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView gifImageView = new ImageView(MainActivity.this);
                GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(gifImageView);
                Glide.with(MainActivity.this).load(R.raw.test).into(imageViewTarget);

                AlertDialog.Builder share_dialog = new AlertDialog.Builder(MainActivity.this);
                share_dialog.setMessage("GIF Test");
                share_dialog.setPositiveButton("Done", null);
                share_dialog.setView(gifImageView);
                share_dialog.show();
            }
        });
    }

After running this project.

GIF can display in imageView_main, but it can't be shown on AlertDialog's gifImageView !

Why ?


Answer:

Do it like this

ImageView gifImageView = new ImageView(context);

AlertDialog.Builder share_dialog = new AlertDialog.Builder(context);
share_dialog.setMessage("Live Message Saved");
share_dialog.setPositiveButton("Done", null);
share_dialog.setView(gifImageView);
Glide.with(context).load(recorder.getPictureFile()).asGif().into(gifImageView);
share_dialog.show(); 

put your load GLIDE after setting the view.

Question:

I want to add feature in my app to download a GIF Image from url to my phones storage. How can I do this into my application

public class Download {

    Context context;
    String url;
    ProgressDialog progressDailog;

    public void saveImage(Context context, String url) {

        this.context = context;
        this.url = url;

        progressDailog = new ProgressDialog(context);
        progressDailog.setMax(100);
        progressDailog.setMessage("Please wait...");
        progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDailog.setCanceledOnTouchOutside(false);
        progressDailog.show();


        Glide.with(context).asBitmap()
                .load(url)
                .apply(new RequestOptions()
                        .diskCacheStrategyOf(DiskCacheStrategy.ALL)
                        .format(DecodeFormat.PREFER_ARGB_8888)
                        .override(Target.SIZE_ORIGINAL))
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        progressDailog.dismiss();
                        storeImage(resource);
                        //Log.d(TAG, "Image : " + resource);
                    }
                });
    }

    private void storeImage(Bitmap image) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            return;
        }
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
            Toast.makeText(context, "Image Downloaded", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }

    private File getOutputMediaFile() {
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs())
                return null;
        }

        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS.jpg");
        return mediaFile;
    }

}

From this code I can download the normal Image but it did not works on GIF. The GIF image downloaded and it remains static


Answer:

For getting GIF using Glide:

 Glide.with(MainActivity.this).asFile()
            .load(url)
            .apply(new RequestOptions()
                    .format(DecodeFormat.PREFER_ARGB_8888)
                    .override(Target.SIZE_ORIGINAL))
            .into(new Target<File>() {
                @Override
                public void onStart() {

                }

                @Override
                public void onStop() {

                }

                @Override
                public void onDestroy() {

                }

                @Override
                public void onLoadStarted(@Nullable Drawable placeholder) {

                }

                @Override
                public void onLoadFailed(@Nullable Drawable errorDrawable) {

                }

                @Override
                public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                    storeImage(resource);
                }

                @Override
                public void onLoadCleared(@Nullable Drawable placeholder) {

                }

                @Override
                public void getSize(@NonNull SizeReadyCallback cb) {

                }

                @Override
                public void removeCallback(@NonNull SizeReadyCallback cb) {

                }

                @Override
                public void setRequest(@Nullable Request request) {

                }

                @Nullable
                @Override
                public Request getRequest() {
                    return null;
                }
            });

For Saving Image:

 private void storeImage(File image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        return;
    }
    try {
        FileOutputStream output = new FileOutputStream(pictureFile);
        FileInputStream input = new FileInputStream(image);

        FileChannel inputChannel = input.getChannel();
        FileChannel outputChannel = output.getChannel();

        inputChannel.transferTo(0, inputChannel.size(), outputChannel);
        output.close();
        input.close();
        Toast.makeText(MainActivity.this, "Image Downloaded", Toast.LENGTH_SHORT).show();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private File getOutputMediaFile() {
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs())
            return null;
    }

    File mediaFile;
    mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS_"+Calendar.getInstance().getTimeInMillis() +".gif");
    return mediaFile;
}

Question:

I have an issue with the GIF Resizing. My GIF dimensions is 136*136 px and I'm trying to load it into an image view (that has its width and height set as wrap_content) using Glide library. But the GIF ends up taking the entire screen. My XML file code snippet looks like below:

ImageView
    android:id="@+id/loading_animation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:adjustViewBounds="true"
    tools:src="@drawable/gif_loading_animation"
    android:foregroundGravity="center" />

And My main activity code looks something like this:

Glide.with(getContext())
            .load(R.drawable.gif_loading_animation)
            .asGif()
            .into(loadingAnimation);

Is there any solution to avoid resizing without using any hard code parameters width and height. :)


Answer:

You can try using .override(Target.SIZE_ORIGINAL)

    Glide.with(getContext())
     .load(R.drawable.gif_loading_animation)
     .asGif()
     .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
     .into(loadingAnimation);

Question:

I have a set of images, loaded via Glide.

The NSFW ones are blurred using a glide (wasabeef) bitmap transformation, however some can be animated gifs, in which case the first frame is shown blurred, and then the animation starts looping (unblurred).

The following is what I have tried and does not work:

DrawableTypeRequest<String> builder = Glide.with(mImage.getContext()).load(...);

if (entry.isNsfw()) {
    builder.asBitmap();
}

builder.diskCacheStrategy(DiskCacheStrategy.SOURCE) //it's likely none of this is relevant
    .skipMemoryCache(true)
    .override(props.getWidth(), props.getHeight());

if (entry.isNsfw()) {
    //successfully blurs nsfw images, but still allows unblurred animation
    builder.dontAnimate().bitmapTransform(centreCrop, blur);
} else {
    builder.centerCrop();
}

builder.crossFade(500) //moving crossfade only into the sfw posts has no effect
       .into(mImage);

Also not working is intercepting the load:

builder.listener(new RequestListener<String, GlideDrawable>() {
    @Override
    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
        return false;
    }

    @Override
    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
        if (entry.isNsfw()) {
            target.onResourceReady(resource, null); //If I add this and return true the image is static, but unblurred
            resource.stop(); //if this is called before target, it has no effect
            return true;
        }
        return false; //returning true without calling the target stops any of the images being set on the view
    }
});

How can I turn off the gif playback for individual images while still keeping the blur transformation?


Answer:

In the end mixing a few of the steps I outlined in my question, fixed the issue. Animated NSFW gifs now display only the first frame, which is successfully blurred.

DrawableRequestBuilder<String> builder = Glide.with(ctx).load(...);
if (nsfw) {
    builder.bitmapTransform(new BlurTransformation(ctx, 8, 16), new CentreCrop(...));
} else {
    builder.centerCrop();
}
builder.listener(new RequestListener<String, GlideDrawable>() {
    ... //onException method
    @Override
    public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
        boolean handled = false;
        if (nsfw && resource.isAnimated()) {
            target.onResourceReady(new GlideBitmapDrawable(null, ((GifDrawable) resource).getFirstFrame()), null);
            handled = true; //glide now won't set the resource on the target itself
        }
        return handled;
    }
});
builder.crossFade(500).into(mImageView);

Question:

I have a list of animated gifs in drawable resource folder in my android project. I need these gifs played one by one, wait for seconds, and then play the next gif. but when I run the app, all gifs load very very fast so I can just see the last gif. I used Glide for playing gifs and this is my code

Handler handler1 = new Handler();        

for (int a = 1; a<=lines.size() ;a++) {
    handler1.postDelayed(new Runnable() {

        @Override
        public void run() {
            String resName = "";
            int duration = 0;
            resName = "wo_" + (lines.get(slideIndex).split(",")[0]).toLowerCase().trim().replace(".gif", "");
            duration = Integer.parseInt(lines.get(slideIndex++).split(",")[2].trim());
            int resourceId = getResId(resName, R.drawable.class);//this.getResources().getIdentifier(resName, "drawable", this.getPackageName());

            Glide.with(WorkoutActivity.this).asGif().load(resourceId).into(imageView);
        }
    }, 5000);
}

Answer:

You can use Timer for this

   // Declare globally
private int position = -1;

/**
 * This timer will call each of the seconds.
 */
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
    @Override
    public void run() {
        // As timer is not a Main/UI thread need to do all UI task on runOnUiThread
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                    // increase your position so new image will show
                position++;
                // check whether position increased to length then set it to 0
                // so it will show images in circuler
                if (position >= imageArray.length)
                    position = 0;
                // Set Image
                MyImageView.setImageResource(imageArray[position]);
            }
        });
    }
}, 0, 5000);

Question:

My code is like this:

String gifUrl = "http://i.kinja-img.com/gawker-media/image/upload/s--B7tUiM5l--/gf2r69yorbdesguga10i.gif";


Glide
   .with( mContext )
   .load( gifUrl )
   .error( R.drawable.sample )
   .into( imageViewTarget );

imageViewTarget is a normal imageview. But it is not loading the gif in the imageview.


Answer:

It works but may take time in loading gif.

ImageView imageView = (ImageView) findViewById(R.id.imageView);
    GlideDrawableImageViewTarget imageViewPreview = new GlideDrawableImageViewTarget(imageView);
    Glide.with(this)
            .load("http://i.kinja-img.com/gawker-media/image/upload/s--B7tUiM5l--/gf2r69yorbdesguga10i.gif")
            .listener(new RequestListener<String, GlideDrawable>() {
                @Override
                public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                    Log.e("MyApp", "onException: "+model+" Exception: "+e );
                    return false;
                }

                @Override
                public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    Log.e("MyApp", "onResourceReady: "+model );
                    return false;
                }
            })
            .into(imageViewPreview);

Question:

Is it possible to show GIF and also JPG image on the same adapter using Glide? If it is possible, then how code looks like in Glide?


Answer:

You can do like this

String str = "image or gif url";
        if (str.contains(".gif")){
            Glide.with(this)
                    .asGif()
                    .load(str)
                    .into(imgeview);
        }else{
            Glide
                    .with(this)
                    .load(str)
                    .centerCrop()
                    .into(myImageView);
        }

Question:

How can I remove white background around image when loading with glide.. You can find out below code as well as screenshot;

  Glide.with(thiscontext).load(R.drawable.badge_green_yellow)
 .asGif().crossFade()
 .diskCacheStrategy(DiskCacheStrategy.SOURCE).into(holder.ivHourlyIcon);

ScreenShot


Answer:

Put your GIF into the raw folder (res/raw/badge_green_yellow.gif)

and then load it like this

Glide.with(thiscontext).asGif().load(R.raw.badge_green_yellow).into(holder.ivHourlyIcon);

Question:

I am using Glide to load a gif file from url, however it keeps looping. is there anyway to set a counter for looping for example just to play the animation 1 time.


Answer:

You may try like this -

Glide.with(getContext())
        .load(R.drawable.some_gif)
        .into(new GifDrawableImageViewTarget(mGifView, 1));

Question:

I want to show random gif images with Glide library .

I have four gif images . Every time i want to show different gif images (out of four gif images) when app is open ?

For single gif image with glide i have used below code-

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
    GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imageView);
    Glide.with(this).load(R.drawable.dancingbanana).into(imageViewTarget);
}

activiy_main

<ImageView
android:id="@+id/my_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

Answer:

You should make an array of drawables within your values directory res/values/arrays.xml

<array name="gif_drawables">
    <item>@drawable/gif_1</item>
    <item>@drawable/gif_2</item>
    <item>@drawable/gif_3</item>
    <item>@drawable/gif_4</item>
</array>

and then simply select it by doing:

TypedArray images = getResources().obtainTypedArray(R.array.gif_drawables);
int choice = (int) (Math.random() * images.length());
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(imageView);
Glide.with(this).load(images.getResourceId(choice, R.drawable.gif_1)).asGif().into(imageViewTarget);
images.recycle();

Also noted in this answer: how to select from resources randomly (R.drawable.xxxx)


What this does:

  • Creates an XML array (as you know how many gifs you want)
  • Creates a TypedArray object with said array.
  • It then uses the Math class to generate a random integer based on the length of the TypedArray.
  • With that selection it then gets the resource id based on that position (in this case called choice)
  • Finally to help memory management, it then recycles the array after use.

To expand on my comment:

You should use the asGif() function introduced with Glide 3.0 also.