【发布时间】:2010-11-12 19:58:54
【问题描述】:
给定一个图像的 URL,我想下载它并将其粘贴到我的 android 画布上。如何将图像检索到我的应用程序中?
请帮忙。
谢谢, 德科斯托。
【问题讨论】:
标签: android
给定一个图像的 URL,我想下载它并将其粘贴到我的 android 画布上。如何将图像检索到我的应用程序中?
请帮忙。
谢谢, 德科斯托。
【问题讨论】:
标签: android
Android 现在可能支持一个 HTTP 客户端库,但对于任何细粒度控制,您都可以使用 URL 和 HttpURLConnection。代码将如下所示:
URL connectURL = new URL(<your URL goes here>);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn);
其中 getResponse() 看起来像这样,在你的情况下你得到 一堆二进制数据,你可能想把 StringBuffer 改成字节数组 并以更大的增量对读取进行分块。
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e(TAG, "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
当您谈论可能很大的图像数据时,您需要在 Android 中认真考虑的其他事情是确保您尽快释放内存,您只有 16mb 的堆可供使用所有应用程序都很快用完,如果你不擅长回馈内存资源,GC 会让你发疯
【讨论】:
您可以使用以下代码下载图片:
URLConnection connection = uri.toURL().openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
Bitmap bmp = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
在 AndroidManifest.xml 中需要以下权限:
<uses-permission android:name="android.permission.INTERNET" />
【讨论】:
别忘了给应用程序连接网络的权限,
在 AndroidManifest.xml 中:
<uses-permission android:name="android.permission.INTERNET" />
【讨论】: