Solution to BitmapFactory decodeStream null

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

  1. ..... 
  2.  
  3. Bitmap bitmap=BitmapFactory.decodeStream(inputStream); 
  4.  
  5. .... 

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

網上類似的問題:

http://stackoverflow.com/questions/3802820/bitmapfactory-decodestream-always-returns-null-and-skia-decoder-shows-decode-ret

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

http://code.google.com/p/android/issues/detail?id=6066

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

解決方法:

  1. static class FlushedInputStream extends FilterInputStream { 
  2.     public FlushedInputStream(InputStream inputStream) { 
  3.         super(inputStream); 
  4.     } 
  5.  
  6.     @Override 
  7.     public long skip(long n) throws IOException { 
  8.         long totalBytesSkipped = 0L; 
  9.         while (totalBytesSkipped < n) { 
  10.             long bytesSkipped = in.skip(n - totalBytesSkipped); 
  11.             if (bytesSkipped == 0L) { 
  12.                 int bytes = read(); 
  13.                 if (bytes < 0) { 
  14.                     break// we reached EOF 
  15.                 } else { 
  16.                     bytesSkipped = 1// we read one byte 
  17.                 } 
  18.             } 
  19.             totalBytesSkipped += bytesSkipped; 
  20.         } 
  21.         return totalBytesSkipped; 
  22.     } 

或者另外建個類。

以前的代碼改爲:

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

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章