Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transparent GIF in Android ImageView

I am trying to display the transparent GIF image in my app with no success. I can get to download and display the icon in an ImageView but with white background instead of transparent.

I have already tried these solutions with no sucess: Convert GIF to PNG programatically

Has anyone figured out how to display the GIF image with transparency? I am using the Android 18 SDK.

like image 303
netcyrax Avatar asked Nov 18 '13 19:11

netcyrax


People also ask

How do you make a GIF transparent on android?

You can use GifDecoder from android-gifview instead of BitmapFactory to decode GIFs: GifDecoder gd = new GifDecoder(); gd. read(new FileInputStream(filename)); return gd. getBitmap();

Can I use GIF in Android Studio?

Android App Development for Beginners This example demonstrates how do I display animated gif images in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

Does Picasso support GIF?

Picasso does not support GIF animation on a simple image view.


1 Answers

Here is a workaround that has worked for me. It is not a good solution. It may not work in all cases and there is significant overhead in image processing. Hopefully someone else will find a better solution.

In my testing, GIF images in 4.4 have transparency values as either white (-1) or black (-16777216). After you load a Bitmap, you can convert the white/black pixels back to transparent. Of course this will only work if the rest of the image doesn't use the same color. If it does then you will also convert parts of your image to transparent that were not transparent in the original image. In my case this wasn't a problem.

You can use the following code to convert either white or black pixels to transparent.

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap = eraseBG(bitmap, -1);         // use for white background
bitmap = eraseBG(bitmap, -16777216);  // use for black background


private static Bitmap eraseBG(Bitmap src, int color) {
    int width = src.getWidth();
    int height = src.getHeight();
    Bitmap b = src.copy(Config.ARGB_8888, true);
    b.setHasAlpha(true);

    int[] pixels = new int[width * height];
    src.getPixels(pixels, 0, width, 0, 0, width, height);

    for (int i = 0; i < width * height; i++) {
        if (pixels[i] == color) {
            pixels[i] = 0;
        }
    }

    b.setPixels(pixels, 0, width, 0, 0, width, height);

    return b;
}

Note: I had to copy the Bitmap to a new ARGB_8888 image for this to work. Even when loading the bitmap as mutable, I still couldn't modify the pixels. This is partly why there is so much overhead.

like image 100
paul Avatar answered Oct 11 '22 16:10

paul