亲爱的所有我使用下面的代码下载android中的图片, 其中_in是Input Stream和DataInputStream _din。 我使用一个URL下载图片。但有时它会返回我的图片,有时它不会在位图中显示null。我在这里有一个问题,一个是下载图片的好方法或建议在这张图片中可能出错的相同代码有时返回图片,有时它不起作用?
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 :(得分: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();
}
}
答案 1 :(得分:0)
为什么要为图像 InputStream 使用临时缓冲区?只需将UrlConnection InputStream直接与BitmapFactory一起使用:
_in = urlConnection.getInputStream();
Bitmap bmp = BitmapFactory.decodeStream(_in);
如果图像合适,这应该始终有效。