如何从App中的URL下载图像

San*_*oid 2 android

我想知道如何从给定的URL下载图像并将其显示在ImageView中.是否有permissions必要在manifest.xml文件中提及?

MKJ*_*ekh 7

您需要将其设置permission为访问Internet

<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)

你可以尝试这个代码.

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);  
Run Code Online (Sandbox Code Playgroud)