Extract Bitmap frames from GIF file Android
Sep 8, 2018 · 1 min read
Wow, it was really hard to find any solution in Google, almost few days i spent to get something, related topic. But didn't get any luck.
So what I have — correctly extract frame by frame from GIF file inside Bitmap objects and then show them in 3-rd view.
Non of well know libraries like Picasso (https://github.com/square/picasso), Fresco (https://github.com/facebook/fresco) , Glide(https://github.com/bumptech/glide) does not have any public methods or documentation.
Anyway, we will use non-documented methods from Glide and i hope in one day Glide team will make it public. You will need to have a bit experience with Java Reflection :) Here is bench of code to extract Bitmap from GIF file:
ArrayList bitmaps = new ArrayList<>();
Glide.with(AppObj.getContext())
.asGif()
.load(GIF_PATH)
.into(new SimpleTarget<GifDrawable>() {
@Override
public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {
try {
Object GifState = resource.getConstantState();
Field frameLoader = GifState.getClass().getDeclaredField("frameLoader");
frameLoader.setAccessible(true);
Object gifFrameLoader = frameLoader.get(GifState);
Field gifDecoder = gifFrameLoader.getClass().getDeclaredField("gifDecoder");
gifDecoder.setAccessible(true);
StandardGifDecoder standardGifDecoder = (StandardGifDecoder) gifDecoder.get(gifFrameLoader);
for (int i = 0; i < standardGifDecoder.getFrameCount(); i++) {
standardGifDecoder.advance();
bitmaps.add(standardGifDecoder.getNextFrame());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}Enjoy!
