如何在 Android 中通过 URL 加载 ImageView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2471935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 05:59:09  来源:igfitidea点击:

How to load an ImageView by URL in Android?

androidbitmapimageview

提问by Praveen

How do you use an image referenced by URL in an ImageView?

您如何使用 .url 中的 URL 引用的图像ImageView

采纳答案by Praveen

Anyway people ask my comment to post it as answer. i am posting.

无论如何,人们要求我的评论将其发布为答案。我在发帖。

URL newurl = new URL(photo_url_str); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);

回答by Android Developer

From Android developer:

来自Android 开发者

// show The Image in a ImageView
new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
            .execute("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");

public void onClick(View v) {
    startActivity(new Intent(this, IndexActivity.class));
    finish();

}

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);
    }
}

Make sure you have the following permissions set in your AndroidManifest.xmlto access the internet.

确保您设置了以下AndroidManifest.xml访问互联网的权限。

<uses-permission android:name="android.permission.INTERNET" />

回答by chiragkyada

1.Picassoallows for hassle-free image loading in your application—often in one line of code!

1. Picasso允许在您的应用程序中轻松加载图像——通常只需一行代码!

Use Gradle:

使用摇篮:

implementation 'com.squareup.picasso:picasso:2.71828'

Just one line of code!

只需一行代码!

Picasso.get().load("http://i.imgur.com/DvpvklR.png").into(imageView);

2.GlideAn image loading and caching library for Android focused on smooth scrolling

2. Glide一个专注于平滑滚动的Android图片加载和缓存库

Use Gradle:

使用摇篮:

repositories {
  mavenCentral() 
  google()
}

dependencies {
   implementation 'com.github.bumptech.glide:glide:4.7.1'
   annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
}

// For a simple view:

// 对于一个简单的视图:

  Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

3.frescois a powerful system for displaying images in Android applications.Fresco takes care of image loading and display, so you don't have to.

3. fresco是一个强大的系统,用于在 Android 应用程序中显示图像。Fresco 负责图像加载和显示,因此您不必这样做。

Getting Started with Fresco

Fresco 入门

回答by Steve

You'll have to download the image firstly

您必须先下载图像

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        //options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }

    return bitmap;
}

Then use the Imageview.setImageBitmap to set bitmap into the ImageView

然后使用 Imageview.setImageBitmap 将位图设置到 ImageView 中

回答by koush

I wrote a class to handle this, as it seems to be a recurring need in my various projects:

我写了一个类来处理这个问题,因为它似乎是我各种项目中反复出现的需求:

https://github.com/koush/UrlImageViewHelper

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper will fill an ImageView with an image that is found at a URL.

The sample will do a Google Image Search and load/show the results asynchronously.

UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.

UrlImageViewHelper 将使用在 URL 中找到的图像填充 ImageView。

该示例将执行 Google 图片搜索并异步加载/显示结果。

UrlImageViewHelper 将自动下载、保存和缓存 BitmapDrawables 的所有图像 url。重复的 url 不会两次加载到内存中。位图内存使用弱引用哈希表进行管理,因此一旦您不再使用该图像,它将自动进行垃圾回收。

回答by Kyle Clegg

The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.

如果您基于单击按钮加载图像,则上面接受的答案很好,但是如果您在新活动中执行此操作,它会冻结 UI 一两秒钟。环顾四周,我发现一个简单的 asynctask 消除了这个问题。

To use an asynctask add this class at the end of your activity:

要使用异步任务,请在活动结束时添加此类:

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);
    }    
}

And call from your onCreate() method using:

并使用您的 onCreate() 方法调用:

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
        .execute(MY_URL_STRING);

The result is a quickly loaded activity and an imageview that shows up a split second later depending on the user's network speed.

结果是一个快速加载的活动和一个图像视图,根据用户的网络速度在几秒钟后显示。

回答by Blundell

You could also use this LoadingImageView view to load an image from a url:

您还可以使用此 LoadingImageView 视图从 url 加载图像:

http://blog.blundellapps.com/imageview-with-loading-spinner/

http://blog.blundellapps.com/imageview-with-loading-spinner/

Once you have added the class file from that link you can instantiate a url image view:

从该链接添加类文件后,您可以实例化一个 url 图像视图:

in xml:

在xml中:

<com.blundell.tut.LoaderImageView
  android:id="@+id/loaderImageView"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  image="http://developer.android.com/images/dialog_buttons.png"
 />

In code:

在代码中:

final LoaderImageView image = new LoaderImageView(this, "http://developer.android.com/images/dialog_buttons.png");

And update it using:

并使用以下方法更新它:

image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");

回答by pragna

public class LoadWebImg extends Activity {

String image_URL=
 "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png";

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       ImageView bmImage = (ImageView)findViewById(R.id.image);
    BitmapFactory.Options bmOptions;
    bmOptions = new BitmapFactory.Options();
    bmOptions.inSampleSize = 1;
    Bitmap bm = LoadImage(image_URL, bmOptions);
    bmImage.setImageBitmap(bm);
   }

   private Bitmap LoadImage(String URL, BitmapFactory.Options options)
   {       
    Bitmap bitmap = null;
    InputStream in = null;       
       try {
           in = OpenHttpConnection(URL);
           bitmap = BitmapFactory.decodeStream(in, null, options);
           in.close();
       } catch (IOException e1) {
       }
       return bitmap;               
   }

private InputStream OpenHttpConnection(String strURL) throws IOException{
 InputStream inputStream = null;
 URL url = new URL(strURL);
 URLConnection conn = url.openConnection();

 try{
  HttpURLConnection httpConn = (HttpURLConnection)conn;
  httpConn.setRequestMethod("GET");
  httpConn.connect();

  if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
   inputStream = httpConn.getInputStream();
  }
 }
 catch (Exception ex)
 {
 }
 return inputStream;
}
}

回答by Abhishek Karande

Hi I have the most easiest code try this

嗨,我有最简单的代码试试这个

    public class ImageFromUrlExample extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);  
            ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
            Drawable drawable = LoadImageFromWebOperations("http://www.androidpeople.com/wp-content/uploads/2010/03/android.png");
            imgView.setImageDrawable(drawable);

    }

    private Drawable LoadImageFromWebOperations(String url)
    {
          try{
        InputStream is = (InputStream) new URL(url).getContent();
        Drawable d = Drawable.createFromStream(is, "src name");
        return d;
      }catch (Exception e) {
        System.out.println("Exc="+e);
        return null;
      }
    }
   }

main.xml

主文件

  <LinearLayout 
    android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
   <ImageView 
       android:id="@+id/ImageView01"
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content"/>

try this

尝试这个

回答by makovkastar

The best modern library for such a task in my opinion is Picassoby Square. It allows to load an image to an ImageView by URL with one-liner:

在我看来,执行此类任务的最佳现代图书馆是Square 的Picasso。它允许使用单行通过 URL 将图像加载到 ImageView:

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);