Search code examples
androidbitmapbitmapfactorycorrupt-data

Corrupted Images From BitmapFactory


Once in a while when I am downloading images, some of them will appear with gray lines as displayed in the sample image below: Example

This tends to happen exclusively on poor network conditions.

My code for decoding images is essentially a modded version of that from UIL:

Bitmap decodedBitmap = BitmapFactory.decodeStream(stream, null, decodingOptions);

where stream is just an InputStream to the remote file

Now I've seen this behaviour on the Google Play Music app which makes me wonder if it's an issue with the BitmapFactory. The only solution I've come up with so far is maybe doing a checksum comparison to make sure the entire image was downloaded.

Edit:

HttpURLConnection conn = getConnection(path);
InputStream inputStream = conn.getInputStream()
stream = new ContentLengthInputStream(new BufferedInputStream(download, BUFFER_SIZE), conn.getContentLength())

Solution

  • Solved it by using the following steps:

    • Open an InputStream to the image as normal
    • Write the stream to a ByteArrayOutputStream
    • Compare the length of the ByteArrayOutputStream to the Content-Length header from the HttpURLConnection
    • If mismatch then you've lost data in transit
    • Otherwise you can convert your ByteArrayOutputStream to a ByteArrayInputStream and use with the BitmapFactory as you see fit