给定一个图像的URL,我想下载它并将其粘贴到我在android上的canvas上。 如何将图像检索到我的应用程序?
请帮忙。
谢谢,de costo。
您可以使用以下代码下载图像:
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中需要以下权限:
别忘了给应用程序提供连接到Web的权限,
在AndroidManifest.xml中:
Android现在可能支持HTTP客户端库,但对于任何细粒度控制,您都可以使用URL和HttpURLConnection。 代码看起来像这样:
URL connectURL = new URL(); 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会让你疯狂