android中使用BitmapFactory的decodeStream()方法解码图片失败问题

从网络获取图片,数据为InputStream流对象,然后调用BitmapFactory的decodeStream()方法解码获取图片。代码如下: 

复制代码
private Bitmap getUrlBitmap(String url)
{
Bitmap bm;
try{
URL imageUrl
=new URL(url);
HttpURLConnection conn
=(HttpURLConnection)imageUrl.openConnection();
conn.connect();
InputStream is
=conn.getInputStream();
//byte[] bt=getBytes(is); //注释部分换用另外一种方式解码
//bm=BitmapFactory.decodeByteArray(bt,0,bt.length);
bm=BitmapFactory.decodeStream(is); //如果采用这种解码方式在低版本的API上会出现解码问题
is.close();
conn.disconnect();
return bm;
}
catch(MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
returnnull;

}
复制代码

结果在运行时编译器提示:          DEBUG/skia(xxx):--- decoder->decode returned false 

已经确定从网络获取的数据流没有出现问题,而是在图片解码时出现错误。上网查找了不少资料,也没有得出确切的原因,不过有几条意见值得关注。

一种说法是在android 较低版本的api中会有不少内部的错误,我的代码运行时选择2.1API Level 7和2.2API Level 8都会出现这个问题,而选择2.3 API Level 9后能够正常解码图片。

我的另外一种做法是换用别的解码方式对图片解码,见代码中被注释的那俩行,使用decodeByteArray()方法在低版本的API上也能够正常解码,解决了这个问题。

其中getBytes(InputStream is)是将InputStream对象转换为Byte[]的方法,具体代码如下:

复制代码
privatebyte[] getBytes(InputStream is) throws IOException {

ByteArrayOutputStream baos
=new ByteArrayOutputStream();
byte[] b =newbyte[1024];
int len =0;

while ((len = is.read(b, 0, 1024)) !=-1)
{
baos.write(b,
0, len);
baos.flush();
}
byte[] bytes = baos.toByteArray();
return bytes;
}
原文地址:https://www.cnblogs.com/zhwl/p/2796626.html