BitmapFactory.decodeStream always returns null and

2019-01-17 19:01发布

test image here: http://images.plurk.com/tn_4134189_bf54fe8e270ce41240d534b5133884ee.gif

I've tried several solutions found on the internet but there is no working solution.

I'm using the following snippet code:

Url imageUrl = new Url("http://images.plurk.com/tn_4134189_bf54fe8e270ce41240d534b5133884ee.gif");
Bitmap image = BitmapFactory.decodeStream(imageUrl.openStream());

Always getting this log:

DEBUG/skia(1441): --- decoder->decode returned false

Any help? Thanks.

EDIT:

Those images failed to be decoded are also can not be shown on a WebView. But can see if open in a Browser.

9条回答
叛逆
2楼-- · 2019-01-17 19:25

Try this as a temporary workaround:

First add the following class:

  public static class PlurkInputStream extends FilterInputStream {

    protected PlurkInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read(byte[] buffer, int offset, int count)
        throws IOException {
        int ret = super.read(buffer, offset, count);
        for ( int i = 2; i < buffer.length; i++ ) {
            if ( buffer[i - 2] == 0x2c && buffer[i - 1] == 0x05
                && buffer[i] == 0 ) {
                buffer[i - 1] = 0;
            }
        }
        return ret;
    }

}

Then wrap your original stream with PlurkInputStream:

Bitmap bitmap = BitmapFactory.decodeStream(new PlurkInputStream(originalInputStream));

Let me know if this helps you.

EDIT:

Sorry please try the following version instead:

        for ( int i = 6; i < buffer.length - 4; i++ ) {
            if ( buffer[i] == 0x2c ) {
                if ( buffer[i + 2] == 0 && buffer[i + 1] > 0
                    && buffer[i + 1] <= 48 ) {
                    buffer[i + 1] = 0;
                }
                if ( buffer[i + 4] == 0 && buffer[i + 3] > 0
                    && buffer[i + 3] <= 48 ) {
                    buffer[i + 3] = 0;
                }
            }
        }

Note that this is not efficient code nor is this a full/correct solution. It will work for most cases, but not all.

查看更多
地球回转人心会变
3楼-- · 2019-01-17 19:31

this is due to a bug in the InputStream class in Android. You can find a valid workaround and a description of the bug here http://code.google.com/p/android/issues/detail?id=6066

查看更多
相关推荐>>
4楼-- · 2019-01-17 19:33

I tried all the solutions but did not solved my problem. After some tests, the problem of skia decoder failing happened a lot when the internet connection is not stable. For me, forcing to redownload the image solved the problem.

The problem also presented more when the image is of large size.

Using a loop will required me at most 2 retries and the image will be downloaded correctly.

Bitmap bmp = null;
int retries = 0;
while(bmp == null){
    if (retries == 2){
        break;
    }
    bmp = GetBmpFromURL(String imageURL);
    Log.d(TAG,"Retry...");
    retries++;
}
查看更多
登录 后发表回答