2012-08-29 88 views
0

亲爱的我用下面的代码下载android中的图片, 其中_in是Input Stream和DataInputStream _din。 我使用一个URL来下载图片,但有时它会返回我的图片,有时它不会在位图中显示null。我在这里有一个问题,一个是这种好的方式来下载图片或建议在这张图片中可能是错误的代码有时会返回图片,有时它不起作用?在android中下载图片

if (_in == null) { 
     _in = urlConnection.getInputStream(); 
    } 
    if (_din == null) { 
     _din = new DataInputStream(_in); 
    } 

    byte[] data = new byte[0]; 
    byte[] buffer = new byte[512]; 
    int bytesRead; 
    while ((bytesRead = _din.read(buffer)) > 0) {   
     byte[] newData = new byte[data.length + bytesRead];   
     System.arraycopy(data, 0, newData, 0, data.length);   
     System.arraycopy(buffer, 0, newData, data.length, bytesRead);   
     data = newData; 
    }  
    InputStream is = new ByteArrayInputStream(data); 
    Bitmap bmp = BitmapFactory.decodeStream(is); 

回答

0

试试这个,告诉我你的问题是否仍然存在。

Bitmap ret; 
     HttpURLConnection conn = null;   
     try 
     { 
      URL u = new URL(mUrl); 
      conn = (HttpURLConnection) u.openConnection(); 
      conn.setConnectTimeout(CONNECTION_TIMEOUT); 
      conn.setReadTimeout(CONNECTION_TIMEOUT); 
      conn.setDoInput(true); 
      conn.setRequestMethod("GET"); 

      int httpCode = conn.getResponseCode(); 
      if (httpCode == HttpURLConnection.HTTP_OK || httpCode == HttpURLConnection.HTTP_CREATED) 
      { 
       InputStream is = new BufferedInputStream(conn.getInputStream()); 
       ret = BitmapFactory.decodeStream(is); 
      } 
      else 
      { 
       ret = null; 
      } 
     } 
     catch (Exception ex) 
     { 
      ret = null; 
     } 
     finally 
     { 
      if (conn != null) 
      { 
       conn.disconnect(); 
      } 
     } 
0

你为什么使用临时缓冲区为你的形象的InputStream?只需直接与BitmapFactory使用的URLConnection的InputStream:

_in = urlConnection.getInputStream(); 
Bitmap bmp = BitmapFactory.decodeStream(_in); 

此,如果你的图片是确定应始终工作。

+0

嗨好提示。 。我做了它的工作。 。做更多的测试以使其回答。 。 – aftab