PlasmaEye PlasmaEye - 4 months ago 53
Android Question

Convert GIF to PNG programatically

I have a GIF that I am grabbing from a website (http://radar.weather.gov/ridge/RadarImg/N0R/) and wanting to display to the user. I am building to Jelly Bean (4.1) and in my searches on this subject found that GIF compatibility is on its way out for Android and flat out doesn't work on Jelly Bean.

So, I want to convert the GIF over to a PNG on the fly. How would I do this? Is it as simple as reading in the bytes from the GIF to a PNG file?

I will be using an ImageView to display the image on the UI.

Answer

After changing my question a bit, I found the answer through the almighty Google here:

http://gayashan-a.blogspot.com/2012/02/android-how-to-display-gif-image-in.html

Summarized here:

public Bitmap getBitmap(String url)
{
    Bitmap bmp = null;
    try
    {
        HttpClient client = new DefaultHttpClient();
        URI imageUri = new URI(url);
        HttpGet req = new HttpGet();
        req.setURI(imageUri);
        HttpResponse resp = client.execute(req);
        bmp = BitmapFactory.decodeStream(resp.getEntity().getContent());            
    }
    catch(URISyntaxException ex)
    {           
        Log.e("ERROR", ex.getMessage());
    }
    catch(ClientProtocolException ex)
    {
        Log.e("ERROR", ex.getMessage());
    }
    catch(IllegalStateException ex)
    {
        Log.e("ERROR", ex.getMessage());
    }
    catch(IOException ex)
    {
        Log.e("ERROR", ex.getMessage());
    }

    return bmp;
}

This decodes it to a Bitmap which can be compressed to a PNG ...

Bitmap mCurrentRadar = getBitmap("http://radar.weather.gov/ridge/RadarImg/N0R/ABC_N0R_0.gif");
ByteArrayOutputStream stream = new ByteArrayOutputStream();     
mCurrentRadar.compress(Bitmap.CompressFormat.PNG, 100, stream);

... or can be immediately used in an ImageView ...

ImageView imageView = (ImageView) findeViewById(R.id.radarImageView);
imageView.setImageBitmap(getBitmap("http://radar.weather.gov/ridge/RadarImg/N0R/ABC_N0R_0.gif");