关于BitmapFactory.decodeStream(is)方法无法正常解码为Bitmap对象的解决方法

如下结果Bitmap为空

Bitmap bitmap=BitmapFactory.decodeStream(result);

mImageViewShow.setImageBitmap(bitmap);

后来调试发现,result为null,加之查看帮助文档中的黑体字, 所以在所获得的InputStream不为空的情况下,调用BitmapFactory.decodeStream(is)方法,他也有可能无法解码成bitmap,刚开始我怀疑是本身图片地址有问题,或图片自身格式不正确,但通过浏览器查看,图片显示正常,而且,我是保存了几十张图片,但每次都会有个别几张图片无法正常显示,需要重复下载三四次,才可能保存成功。

后来在一篇文章中才发现,原来这是android 1.6版本的一个bug!

有牛人提出的一个解决办法,我试了试,问题解决了

首先在原方法中改一句:

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

再创建一个类:`public class PatchInputStream extends FilterInputStream{

protected PatchInputStream(InputStream in) {
  super(in);
  // TODO Auto-generated constructor stub
}

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;
}

}`
第二种方法:最终用的是这种方法

InputStream is = httpConn.getInputStream();


if (is == null){

throw new RuntimeException("stream is null");

}else{

try {

byte[] data=readStream(is);

if(data!=null){

bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

}

} catch (Exception e) {

e.printStackTrace();

}

is.close();

}
 /*
   * 得到图片字节流 数组大小
   * */
  public static byte[] readStream(InputStream inStream) throws Exception{     
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();    
    byte[] buffer = new byte[1024];   
    int len = 0;      
    while( (len=inStream.read(buffer)) != -1){    
      outStream.write(buffer, 0, len);    
    }     
    outStream.close();    
    inStream.close();     
    return outStream.toByteArray();   
  }

或者直接写在一起

  if (result == null) {
                throw new RuntimeException("stream is null");
            } else {
                try {
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    byte[] buffer = new byte[10240];
                    int len = 0;
                    while ((len = result.read(buffer)) != -1) {
                        outStream.write(buffer, 0, len);
                    }
                    outStream.close();
                    result.close();
                    byte[] data=outStream.toByteArray();

                    if (data != null) {
                        Bitmap   bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

                        mImageViewShow.setImageBitmap(bitmap);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值