2014-05-19 67 views
0

我想在後臺線程中從Url加載位圖。我的方法如下所示。BitmapFactory.decodeStream(...)總是返回null作爲位圖

public Bitmap decodeSampledBitmapFromURL(String url,int reqWidth, int reqHeight) { 

     // First decode with inJustDecodeBounds=true to check dimensions 
     final BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inJustDecodeBounds = true; 
     InputStream is=null; 
     try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 
      is = entity.getContent(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Rect rect = new Rect(-1, -1, -1, -1); 
     Bitmap bmp1 = BitmapFactory.decodeStream(is,rect, options); 
     // Calculate inSampleSize 
     options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 

     // Decode bitmap with inSampleSize set 
     options.inJustDecodeBounds = false; 
     Bitmap bmp2 = BitmapFactory.decodeStream(is,rect, options); 
     return bmp2; 
    } 

我總是得到bmp1和bmp2爲空。爲什麼?

+0

你在變量__response__得到一個正確的值來創建新的數據流? –

+0

實際上url是「http://something.jpg」,我無法檢查是否在響應變量中獲得了正確的值。你可以解釋嗎? – donison24x7

回答

0

也許檢查輸入流是否爲空,以判斷是否有錯誤的位圖代碼或獲取輸入流代碼。 也許Rect應該有適當的尺寸?

0

你流與選項的限制,以明顯的位圖解碼出認沽將是無效解碼,然後,你正試圖從位圖相同的流,這是已經在第一解碼解碼使用。您可以嘗試讀取流字節數組緩衝區,然後包裹bytearrayInputstreams,記得每個解碼

+0

可以請你舉例說明 – donison24x7