天天看點

Solution to BitmapFactory decodeStream null

 最近遇到從網絡上下載下傳圖檔,解碼一直是null的問題:

..... 

Bitmap bitmap=BitmapFactory.decodeStream(inputStream); 

.... 

開始時以為TimeOut太短,或者buffersize太小的問題,修改後仍然沒有解決問題,記得同樣的方法以前下載下傳圖檔挺正常的,Google之,找到了問題的答案,起碼解決了我的問題。

網上類似的問題:

<a href="http://stackoverflow.com/questions/3802820/bitmapfactory-decodestream-always-returns-null-and-skia-decoder-shows-decode-ret">http://stackoverflow.com/questions/3802820/bitmapfactory-decodestream-always-returns-null-and-skia-decoder-shows-decode-ret</a>

原來是系統bug,2.1版本中仍存在這個問題:

<a href="http://code.google.com/p/android/issues/detail?id=6066">http://code.google.com/p/android/issues/detail?id=6066</a>

The problem was indeed in the calls to the InputStream skip() method.

解決方法:

static class FlushedInputStream extends FilterInputStream { 

    public FlushedInputStream(InputStream inputStream) { 

        super(inputStream); 

    } 

    @Override 

    public long skip(long n) throws IOException { 

        long totalBytesSkipped = 0L; 

        while (totalBytesSkipped &lt; n) { 

            long bytesSkipped = in.skip(n - totalBytesSkipped); 

            if (bytesSkipped == 0L) { 

                int bytes = read(); 

                if (bytes &lt; 0) { 

                    break; // we reached EOF 

                } else { 

                    bytesSkipped = 1; // we read one byte 

                } 

            } 

            totalBytesSkipped += bytesSkipped; 

        } 

        return totalBytesSkipped; 

或者另外建個類。

以前的代碼改為:

Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream)); 

遇到同樣問題的童鞋可以參考。

本文轉自 breezy_yuan 51CTO部落格,原文連結:http://blog.51cto.com/lbrant/697374,如需轉載請自行聯系原作者

繼續閱讀