Transparent GIF in Android ImageView

2019-01-22 21:31发布

问题:

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.

回答1:

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.



回答2:

You can use GIMP (opern source GNU software) to convert a GIF to PNG. Install the software, open the GIF, then export it as a PNG.



回答3:

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

It works for me.