今天遇到了一个问题,最终解决,记录下解决方案:
问题:从网络获取图片,数据为InputStream流对象,然后调用BitmapFactory的decodeStream()方法解码获取图片,返回null。
-------------------------------------------------
代码如下:
- 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();
- }
- return null;
- }
结果在运行时编译器提示: DEBUG/skia(xxx):--- decoder->decode returnedfalse
已经确定从网络获取的数据流没有出现问题,而是在图片解码时出现错误。
经上网查阅资料得知,这个android 的一个bug 。在android 2.2 以下(包括2.2) 用 BitmapFactory.decodeStream() 这个方法,会出现概率性的解析失败的异常。而在高版本中,eg 2.3 则不会出现这种异常。
各种百度、各种谷歌、各种分析问题的过程就不再多说了,这里直接说一个解决方法,如下:
- //定义一个根据图片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);