问题描述:
从网络获取图片,数据为InputStream流对象,然后调用BitmapFactory的decodeStream()方法解码获取图片,返回null。
代码如下:
private Bitmap getUrlBitmap(String url) { Bitmap bm; try { URL imageUrl = new URL(url); InputStream is = imageUrl .openStream(); bm = BitmapFactory.decodeStream(is); // 如果采用这种解码方式在低版本的API上会出现解码问题 is.close(); return bm; } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
解决办法:定义一个根据图片url获取InputStream的方法
public static byte[] getBytes(InputStream is) throws IOException { ByteArrayOutputStream outstream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; // 用数据装 int len = -1; while ((len = is.read(buffer)) != -1) { outstream.write(buffer, 0, len); } outstream.close(); // 关闭流一定要记得。 return outstream.toByteArray(); }
然后使用方法decodeByteArray()方法解析编码,生成Bitmap对象
byte[] data = getBytesFromInputStream(new URL(imgUrl).openStream()); Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);