【发布时间】:2017-12-02 05:22:03
【问题描述】:
我想知道如何从给定的 URL 下载图像并将其显示在 ImageView 中。 manifest.xml 文件中是否需要提及 permissions?
【问题讨论】:
-
查看这个适合初学者的不错的教程:Connecting to the Web: I/O Programming in Android.
标签: android
我想知道如何从给定的 URL 下载图像并将其显示在 ImageView 中。 manifest.xml 文件中是否需要提及 permissions?
【问题讨论】:
标签: android
你需要输入这个permission才能上网
<uses-permission android:name="android.permission.INTERNET" />
你可以试试这个代码。
String imageurl = "YOUR URL";
InputStream in = null;
try
{
Log.i("URL", imageurl);
URL url = new URL(imageurl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.connect();
in = httpConn.getInputStream();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
Bitmap bmpimg = BitmapFactory.decodeStream(in);
ImageView iv = "YOUR IMAGE VIEW";
iv.setImageBitmap(bmpimg);
【讨论】:
使用后台线程获取图像,并在获取图像后使用 hanndler 在 imageview 中设置它。
new Thread(){
public void run() {
try {
Bitmap bitmap = BitmapFactory.decodeStream(new URL("http://imageurl").openStream());
Message msg = new Message();
msg.obj = bitmap;
imageHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
我们在 imgaeview 中设置下载图像的处理程序代码。
Handler imageHandler = new Handler(){
public void handleMessage(Message msg) {
if(msg.obj!=null && msg.obj instanceof Bitmap){
imageview.setBackgroundDrawable(new BitmapDrawable((Bitmap)msg.obj));
}
};
};
当然你需要互联网许可。
<uses-permission android:name="android.permission.INTERNET" />
【讨论】:
您需要在android manifest文件中设置INTERNET的usage权限,并使用java.net.URL和java.net.URLConnection类对request的URL。
【讨论】:
BitmapFactory-class 可以做到这一点。它可以从InputStream 创建一个Bitmap 对象,然后可以在ImageView 中显示。
您应该知道的是,使用普通的URLConnection 在URL 对象上获取InputStream 并不总是适用于位图工厂。此处提供了一种解决方法:Android: Bug with ThreadSafeClientConnManager downloading images
【讨论】:
看这个:
选项 A:
public static Bitmap getBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bm;
}
选项 B:
public Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
input.close();
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
只需在后台线程中运行该方法即可。
【讨论】: