Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BitmapFactory.decodeStream(inputStream) always return null when some bytes are wrong

I'm building an android app and I'm currently having trouble retrieving a bitmap from an URL. Here is the code I'm using :

public static Bitmap bmpFromURL(URL imageURL){

    Bitmap result = null;

    try {

        HttpURLConnection connection = (HttpURLConnection)imageURL .openConnection();

        connection.setDoInput(true);

        connection.connect();

        InputStream input = connection.getInputStream();

        result = BitmapFactory.decodeStream(input);


    } catch (IOException e) {


        e.printStackTrace();

    }

    return result;

}

Everything works fine when the picture's write but when some bytes are wrong, result gets null. I think it's basically expectable as it's written this in the doc of BitmapFactory.decodeStream :

If the input stream is null, or cannot be used to decode a bitmap, the function returns null. The stream's position will be where ever it was after the encoded data was read.

The problem is, my wrong picture is well interpreted by my web browser and I can do so on iPhone platform.

Is there a way to sort of ignore those wrong pixels? maybe with the option parameter?

Any help appreciated

Romain

like image 991
Romain Piel Avatar asked Dec 20 '25 14:12

Romain Piel


2 Answers

This is a known bug fixed in a future version of Android. You can work around it by first copying the content of the InputStream into a byte[] array and then decoding the byte array itself.

like image 192
Romain Guy Avatar answered Dec 23 '25 04:12

Romain Guy


Try this one out..It worked for me. hope it helps.

result = BitmapFactory.decodeStream(new PatchInputStream(input));

public class PatchInputStream extends FilterInputStream {
   public PatchInputStream(InputStream input) {
       super(input);
   }
   public long skip(long n) throws IOException {
       long m = 0L;
       while (m < n) {
           long _m = in.skip(n-m);
           if (_m == 0L) break;
           m += _m;
       }
       return m;
   }
}
like image 34
Kunila Avatar answered Dec 23 '25 04:12

Kunila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!