如何在安卓设备上显示来自URL的图片

74
我想在屏幕上显示一张图片,这张图片应该来自URL而不是drawable。
代码在下面:
<ImageView android:id="@+id/ImageView01" android:src = "http://l.yimg.com/a/i/us/we/52/21.gif"
    android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>

但在编译时会出现错误。

如何在Android中显示来自URL的图像?

10个回答

114

您可以直接从网络上展示图像,无需下载。请查看下面的函数。它将把网络上的图像展示到您的图像视图中。

public static Drawable LoadImageFromWebOperations(String url) {
    try {
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
    } catch (Exception e) {
        return null;
    }
}

然后在您的活动中使用代码将图像设置为imageview。


2
@ChiragPatel:也许这个链接可以回答你的问题:https://dev59.com/D2025IYBdhLWcg3wQDhb#6127377 - Abdul Rahman
15
需要互联网权限。 - Pratik Butani
3
在这种情况下,“src名称”是什么? - Sauron
7
对于那些想知道什么是"src name"的人,除非与9patch一起使用,否则这个变量毫无用处。请看https://dev59.com/D2025IYBdhLWcg3wQDhb - zgc7009
13
小心那个讨厌的 android.os.NetworkOnMainThreadException - Felix
如果在加载图像时断开互联网连接,则会显示一半。如何知道是否已完全下载图像? - Salmaan

25
我尝试了这段代码,它对我有效,可以直接从URL获取图像。
      private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;
      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
    }

在onCreate()方法内使用

new DownloadImageTask((ImageView) findViewById(R.id.image)) .execute("http://scoopak.com/wp-content/uploads/2013/06/free-hd-natural-wallpapers-download-for-pc.jpg");


代码可以正常运行,但我不得不添加以下内容:<manifest ...> <application ... android:usesCleartextTraffic="true" ...> ... </application> </manifest>以避免出现“不允许明文 HTTP 流量”的问题 (请参见 https://dev59.com/w1cO5IYBdhLWcg3wWgU0) - Razvan_TK9692
1
这让我发疯!为什么对我不起作用! - stefanosn

16

你可以尝试使用 Picasso,它非常好用和易于上手。 不要忘记在清单文件中添加权限。

Picasso.with(context)
                     .load("http://ImageURL")
                     .resize(width,height)
                     .into(imageView );
您还可以在此处查看教程: Youtube / Github

16

你可以尝试这个解决方案,我在另一个问题中找到了它。

Android,使URL上的图像等于ImageView的图像

try {
  ImageView i = (ImageView)findViewById(R.id.image);
  Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
  i.setImageBitmap(bitmap); 
} catch (MalformedURLException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
}

1
你导入了必要的文件吗?例如java.io.IOException等。 - DzMonster
1
如果您的设备运行在3.x或4.x版本上,您需要使用handler或asynctask将下载操作移出UI线程。因为下载操作在UI线程中被禁止。这篇博客可能会有所帮助:http://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html。 - DzMonster

6

4

我使用以下代码从URL中重新获取图像并将其存储在SD卡上:

public String Downloadfromurl(String Url)
{

 String filepath=null;

 try {

  URL url = new URL(Url);

  //create the new connection

  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

  //set up some things on the connection
  urlConnection.setRequestMethod("GET");

  urlConnection.setDoOutput(true); 

   //and connect!

  urlConnection.connect();

  //set the path where we want to save the file
  //in this case, going to save it on the root directory of the
  //sd card.

  folder = new File(Environment.getExternalStorageDirectory().toString()+"/img");

  folder.mkdirs();

  //create a new file, specifying the path, and the filename
  //which we want to save the file as.

  String filename= "page"+no+".PNG";   

  file = new File(folder,filename);

  if(file.createNewFile())

  {

   file.createNewFile();

  }

  //this will be used to write the downloaded data into the file we created
  FileOutputStream fileOutput = new FileOutputStream(file);

  //this will be used in reading the data from the internet
  InputStream inputStream = urlConnection.getInputStream();

  //this is the total size of the file
  int totalSize = urlConnection.getContentLength();
  //variable to store total downloaded bytes
  int downloadedSize = 0;

  //create a buffer...
  byte[] buffer = new byte[1024];
  int bufferLength = 0; //used to store a temporary size of the buffer

  //now, read through the input buffer and write the contents to the file
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
   //add the data in the buffer to the file in the file output stream (the file on the sd card
   fileOutput.write(buffer, 0, bufferLength);
   //add up the size so we know how much is downloaded
   downloadedSize += bufferLength;
   //this is where you would do something to report the prgress, like this maybe
   Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
  }
  //close the output stream when done
  fileOutput.close();
  if(downloadedSize==totalSize)  
      filepath=file.getPath();

 //catch some possible errors...
 } catch (MalformedURLException e) {
  e.printStackTrace();
 } catch (IOException e) {
  filepath=null;
  e.printStackTrace();
 }
 Log.i("filepath:"," "+filepath) ;


 return filepath;

}

如果您想要从SD卡中显示图像,请使用以下代码: Bitmap bmp = BitmapFactory.decodeFile(folder + "/page"+no+".PNG"); imgview.setImageBitmap(bmp); - GK_

4
InputStream URLcontent = (InputStream) new URL(url).getContent();
Drawable image = Drawable.createFromStream(URLcontent, "your source link");

这对我很有效


1
你的“源链接”基本上是什么?我有一个Google的图像URL,我想让这个图像在上面使用的图像视图中加载,但它返回null?如何解决这个问题? - Saad Bilal
这将回答这个问题。 - 0xC0DED00D
2
“url” 和 “你的源链接” 是一样的吗? - zionpi

2

使用 ASyncTask 编写代码处理 HTTP 请求。

Bitmap b;
ImageView img;
......
try
    {
        URL url = new URL("http://10.119.120.10:80/img.jpg");
        InputStream is = new BufferedInputStream(url.openStream());
        b = BitmapFactory.decodeStream(is);
    } catch(Exception e){}
......
img.setImageBitmap(b);

1

我有同样的问题。我测试了这段代码并且它运行良好。这段代码从URL获取图像并将其放入“bmpImage”中。

URL url = new URL("http://your URL");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(60000 /* milliseconds */);
            conn.setConnectTimeout(65000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            //Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();


            BufferedInputStream bufferedInputStream = new BufferedInputStream(is);

            Bitmap bmpImage = BitmapFactory.decodeStream(bufferedInputStream);

-1

虽然链接可能很有用,但最好直接在SO上发布解决方案。 - Pochmurnik
步骤1)转到build.gradle并复制粘贴这两个依赖项 1)implementation 'com.github.bumptech.glide:glide:4.9.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' 然后在您的相对布局中创建一个ImageView。 3)将此代码放入您的Java文件中。 - klaus19

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接