最近遇到从网络上下载图片,解码一直是null的问题:
- .....
- Bitmap bitmap=BitmapFactory.decodeStream(inputStream);
- ....
开始时以为TimeOut太短,或者buffersize太小的问题,修改后仍然没有解决问题,记得同样的方法以前下载图片挺正常的,Google之,找到了问题的答案,起码解决了我的问题。
网上类似的问题:
原来是系统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.
解决方法:
- static class FlushedInputStream extends FilterInputStream {
- public FlushedInputStream(InputStream inputStream) {
- super(inputStream);
- }
- @Override
- public long skip(long n) throws IOException {
- long totalBytesSkipped = 0L;
- while (totalBytesSkipped < n) {
- long bytesSkipped = in.skip(n - totalBytesSkipped);
- if (bytesSkipped == 0L) {
- int bytes = read();
- if (bytes < 0) {
- break; // we reached EOF
- } else {
- bytesSkipped = 1; // we read one byte
- }
- }
- totalBytesSkipped += bytesSkipped;
- }
- return totalBytesSkipped;
- }
- }
或者另外建个类。
以前的代码改为:
- Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
遇到同样问题的童鞋可以参考。