560

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

4

23 回答 23

731

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

确保您在AndroidManifest.xml访问 Internet 时设置了以下权限。

<uses-permission android:name="android.permission.INTERNET" />
于 2012-02-15T05:55:08.087 回答
206

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

使用摇篮:

implementation 'com.squareup.picasso:picasso:(insert latest version)'

只需一行代码!

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

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

使用摇篮:

repositories {
   mavenCentral() 
   google()
}

dependencies {
   implementation 'com.github.bumptech.glide:glide:4.11.0'
   annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
// For a simple view:
Glide.with(this).load("http://i.imgur.com/DvpvklR.png").into(imageView);

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

开始使用 Fresco

于 2014-05-26T08:06:41.480 回答
151

您必须先下载图像

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

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

于 2010-03-18T17:48:23.483 回答
73

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

URL newurl = new URL(photo_url_str); 
mIcon_val = BitmapFactory.decodeStream(newurl.openConnection().getInputStream());
profile_photo.setImageBitmap(mIcon_val);
于 2013-04-30T06:26:36.263 回答
71

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

https://github.com/koush/UrlImageViewHelper

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

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

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

于 2011-04-12T20:20:01.800 回答
64

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

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

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.imageView1))
        .execute(MY_URL_STRING);

结果是一个快速加载的活动和一个稍后显示的图像视图,具体取决于用户的网络速度。

于 2012-06-03T05:31:49.460 回答
25

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

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

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

在 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"
 />

在代码中:

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

并使用以下方法更新它:

image.setImageDrawable("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
于 2010-12-05T12:47:37.743 回答
12

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

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
于 2014-04-17T08:55:15.660 回答
10

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

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

主要的.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"/>

尝试这个

于 2011-12-02T08:48:17.177 回答
10
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;
}
}
于 2011-03-22T10:11:31.680 回答
9

I have recently found a thread here, as I have to do a similar thing for a listview with images, but the principle is simple, as you can read in the first sample class shown there (by jleedev). You get the Input stream of the image (from web)

private InputStream fetch(String urlString) throws MalformedURLException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet request = new HttpGet(urlString);
    HttpResponse response = httpClient.execute(request);
    return response.getEntity().getContent();
}

Then you store the image as Drawable and you can pass it to the ImageView (via setImageDrawable). Again from the upper code snippet take a look at the entire thread.

InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");
于 2011-05-01T07:20:40.743 回答
8

这是一个迟到的回复,正如上面所建议的那样AsyncTask,在谷歌搜索后我找到了解决这个问题的另一种方法。

Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");

imageView.setImageDrawable(drawable);

这是完整的功能:

public void loadMapPreview () {
    //start a background thread for networking
    new Thread(new Runnable() {
        public void run(){
            try {
                //download the drawable
                final Drawable drawable = Drawable.createFromStream((InputStream) new URL("url").getContent(), "src");
                //edit the view in the UI thread
                imageView.post(new Runnable() {
                    public void run() {
                        imageView.setImageDrawable(drawable);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();
}

不要忘记在您AndroidManifest.xml的访问 Internet 中添加以下权限。

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

我自己试过这个,我还没有遇到任何问题。

于 2013-04-09T06:14:33.183 回答
8

这里有很多好的信息......我最近发现了一个名为 SmartImageView 的类,到目前为止它似乎运行良好。非常容易合并和使用。

http://loopj.com/android-smart-image-view/

https://github.com/loopj/android-smart-image-view

更新:我最终写了一篇关于这个的博客文章,所以请查看它以获取有关使用 SmartImageView 的帮助。

第二次更新:我现在总是为此使用毕加索(见上文)并强烈推荐它。:)

于 2012-10-05T16:07:27.667 回答
6
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
于 2012-01-02T05:14:41.577 回答
5

这将帮助你...

定义 imageview 并将图像加载到其中.....

Imageview i = (ImageView) vv.findViewById(R.id.img_country);
i.setImageBitmap(DownloadFullFromUrl(url));

然后定义这个方法:

    public Bitmap DownloadFullFromUrl(String imageFullURL) {
    Bitmap bm = null;
    try {
        URL url = new URL(imageFullURL);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        bm = BitmapFactory.decodeByteArray(baf.toByteArray(), 0,
                baf.toByteArray().length);
    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
    }
    return bm;
}
于 2013-08-05T06:53:25.440 回答
4
    String img_url= //url of the image
    URL url=new URL(img_url);
    Bitmap bmp; 
    bmp=BitmapFactory.decodeStream(url.openConnection().getInputStream());
    ImageView iv=(ImageView)findviewById(R.id.imageview);
    iv.setImageBitmap(bmp);
于 2012-09-15T13:25:55.970 回答
4

带有异常处理和异步任务的版本:

AsyncTask<URL, Void, Boolean> asyncTask = new AsyncTask<URL, Void, Boolean>() {
    public Bitmap mIcon_val;
    public IOException error;

    @Override
    protected Boolean doInBackground(URL... params) {
        try {
            mIcon_val = BitmapFactory.decodeStream(params[0].openConnection().getInputStream());
        } catch (IOException e) {
            this.error = e;
            return false;
        }
        return true;
    }

    @Override
    protected void onPostExecute(Boolean success) {
        super.onPostExecute(success);
        if (success) {
            image.setImageBitmap(mIcon_val);
        } else {
            image.setImageBitmap(defaultImage);
        }
    }
};
try {
    URL url = new URL(url);
    asyncTask.execute(url);
} catch (MalformedURLException e) {
    e.printStackTrace();
}
于 2014-02-28T23:53:51.467 回答
3

试试这个方法,希望这能帮助你解决你的问题。

在这里,我解释了如何使用“AndroidQuery”外部库以 asyncTask 方式从 url/server 加载图像,并将加载的图像缓存到设备文件或缓存区域。

  • 从这里下载“AndroidQuery”库
  • 将此 jar 复制/粘贴到项目 lib 文件夹并将此库添加到项目构建路径
  • 现在我演示如何使用它。

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/imageFromUrl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:adjustViewBounds="true"/>
            <ProgressBar
                android:id="@+id/pbrLoadImage"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"/>

        </FrameLayout>
    </LinearLayout>

MainActivity.java

public class MainActivity extends Activity {

private AQuery aQuery;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    aQuery = new AQuery(this);
    aQuery.id(R.id.imageFromUrl).progress(R.id.pbrLoadImage).image("http://itechthereforeiam.com/wp-content/uploads/2013/11/android-gone-packing.jpg",true,true);
 }
}

Note : Here I just implemented common method to load image from url/server but you can use various types of method which can be provided by "AndroidQuery"to load your image easily.
于 2014-06-10T06:36:23.650 回答
3

在任何容器中为 imageView 工作,例如 listview 网格视图、正常布局

 private class LoadImagefromUrl extends AsyncTask< Object, Void, Bitmap > {
        ImageView ivPreview = null;

        @Override
        protected Bitmap doInBackground( Object... params ) {
            this.ivPreview = (ImageView) params[0];
            String url = (String) params[1];
            System.out.println(url);
            return loadBitmap( url );
        }

        @Override
        protected void onPostExecute( Bitmap result ) {
            super.onPostExecute( result );
            ivPreview.setImageBitmap( result );
        }
    }

    public Bitmap loadBitmap( String url ) {
        URL newurl = null;
        Bitmap bitmap = null;
        try {
            newurl = new URL( url );
            bitmap = BitmapFactory.decodeStream( newurl.openConnection( ).getInputStream( ) );
        } catch ( MalformedURLException e ) {
            e.printStackTrace( );
        } catch ( IOException e ) {

            e.printStackTrace( );
        }
        return bitmap;
    }
/** Usage **/
  new LoadImagefromUrl( ).execute( imageView, url );
于 2014-01-31T09:58:43.033 回答
3
    private Bitmap getImageBitmap(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(bis);
            bis.close();
            is.close();
       } catch (IOException e) {
           Log.e(TAG, "Error getting bitmap", e);
       }
       return bm;
    } 
于 2012-02-06T12:08:05.393 回答
3

一个简单而干净的方法是使用开源库Prime

于 2012-05-02T15:15:44.333 回答
3

此代码经过测试,完全可以正常工作。

URL req = new URL(
"http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png"
);
Bitmap mIcon_val = BitmapFactory.decodeStream(req.openConnection()
                  .getInputStream());
于 2012-09-23T16:10:30.240 回答
3

Android Query 可以为您处理这些以及更多(如缓存和加载进度)。

看看这里

我认为是最好的方法。

于 2013-11-22T13:18:11.110 回答