Assigning Gif Data to Bitmap Object

I've read in numerous places that Android does not have native gif support. As a result, my code is failing on BitmapFactory.decodeByteArray. Here's my code:

URL url = new URL(imgURL); //you can write here any link
HttpURLConnection ucon = (HttpURLConnection)url.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);          

ByteArrayBuffer baf = new ByteArrayBuffer(5000);
int current = 0;
  while ((current = bis.read()) != -1) {
  baf.append((byte) current);
}

image = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.toByteArray().length);

Using the debugger I confirmed the header data is loaded properly and is of GIF format. But once the decode function runs I'm left with a null value. My first guess is that I need to do a GIF -> PNG conversion. How can I do this? Are there other options?

2 Answers

The GifView class at works well. That project is intended for animated gifs, however it works fine with static gifs as well.

1

So despite Android complaining about the GIF and decode failing I think the issue resided through other failures in my code. Changes I made which cause the code to now work.

  1. Made sure I closed the input stream
  2. Removed an incident which could cause infinite looping and thread generation (this was a failure on my parsing rules that pulled out the list of GIF files from an HTML source)
  3. Ensured my storage of the Bitmap files in a List object were always properly casted before being used.

I found help and details through this posting which was an almost identical issue. There are links that follow through on the issue.

In the end I didn't touch my Bitmap or InputStream objects at all, the data was being received properly (as per my confirmation with the GIF header bytes) but was a failure of using the data afterwards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest