安卓BitmapFactory.decodeStream()返回null的問題解決方法
今天遇到了一個問題,最終解決,記錄下解決方案:
問題:從網絡獲取圖片,數據為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);
當然可能還有其他更多的方法,這裏隻分享了一種,有問題大家共同討論,互相分享。
最後更新:2017-04-04 07:03:23