2017-02-01 190 views
1

我們使用下面的函數從URL下載圖像。有時候BitmapFactory.decodeStream我們得到空值。由於這個問題,通知沒有圖像接收。任何一個可以幫助我們解決這個問題..BitmapFactory.decodeStream在下載圖像時返回空值

這是我的代碼:

private Bitmap getImageBitmap(String url) 
{ 
     Bitmap bmsd = null;  
     URL aURL = new URL(url); 
     URLConnection conn = aURL.openConnection(); 
     conn.connect(); 
     InputStream is = conn.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 
     bmsd = BitmapFactory.decodeStream(bis); 
     bis.close(); 
     is.close(); 
     return bmsd; 
} 
+0

退出decodeStream()返回null的正常狀態。如果位圖對可用內存變大,它總是這樣做。 – greenapps

回答

0

嘗試這樣,如果位圖的尺寸過大,我們需要調整的位圖。

private Bitmap getBitmap(String url) 
    { 
     File f=fileCache.getFile(url); 

     //from SD cache 
     Bitmap b = decodeFile(f); 
     if(b!=null) 
      return b; 

     //from web 
     try { 
      Bitmap bitmap=null; 
      URL imageUrl = new URL(url); 
      HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); 
      conn.setConnectTimeout(30000); 
      conn.setReadTimeout(30000); 
      conn.setInstanceFollowRedirects(true); 
      InputStream is=conn.getInputStream(); 
      OutputStream os = new FileOutputStream(f); 
      CopyStream(is, os); 
      os.close(); 
      bitmap = decodeFile(f); 
      return bitmap; 
     } catch (Exception ex){ 
      ex.printStackTrace(); 
      return null; 
     } 
    } 

    //decodes image and scales it to reduce memory consumption 
    private Bitmap decodeFile(File f){ 
     try { 
      //decode image size 
      BitmapFactory.Options o = new BitmapFactory.Options(); 
      o.inJustDecodeBounds = true; 
      BitmapFactory.decodeStream(new FileInputStream(f),null,o); 

      //Find the correct scale value. It should be the power of 2. 
      int width_tmp=o.outWidth, height_tmp=o.outHeight; 
      int scale=1; 
      while(true){ 
       if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE) 
        break; 
       width_tmp/=2; 
       height_tmp/=2; 
       scale*=2; 
      } 

      //decode with inSampleSize 
      BitmapFactory.Options o2 = new BitmapFactory.Options(); 
      o2.inSampleSize=scale; 
      return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); 
     } catch (FileNotFoundException e) {} 
     return null; 
    } 

public static void CopyStream(InputStream is, OutputStream os) 
    { 
     final int buffer_size=1024; 
     try 
     { 
      byte[] bytes=new byte[buffer_size]; 
      for(;;) 
      { 
       int count=is.read(bytes, 0, buffer_size); 
       if(count==-1) 
        break; 
       os.write(bytes, 0, count); 
      } 
     } 
     catch(Exception ex){} 
    } 
+0

但圖像大小隻有50KB以下.... –

相關問題