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

发布于 2024-08-26 09:36:47 字数 48 浏览 6 评论 0原文

如何在 ImageView 中使用 URL 引用的图像?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

地狱即天堂 2024-09-02 09:36:48

我最近发现了一个线程这里< /a>,因为我必须对带有图像的列表视图执行类似的操作,但原理很简单,您可以在其中显示的第一个示例类中阅读(由 jleedev 编写)。
您获取图像的输入流(来自网络)

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

然后将图像存储为Drawable,然后可以将其传递给ImageView(通过setImageDrawable)。再次从上面的代码片段看一下整个线程。

InputStream is = fetch(urlString);
Drawable drawable = Drawable.createFromStream(is, "src");

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");
梦行七里 2024-09-02 09:36:48

这是一个迟到的答复,正如上面所建议的 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 中添加以下权限来访问互联网。

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

This is a late reply, as suggested above AsyncTask will will and after googling a bit i found one more way for this problem.

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

imageView.setImageDrawable(drawable);

Here is the complete function:

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

Don't forget to add the following permissions in your AndroidManifest.xml to access the internet.

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

I tried this myself and i have not face any issue yet.

新雨望断虹 2024-09-02 09:36:48

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

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

< a href="https://github.com/loopj/android-smart-image-view" rel="nofollow noreferrer">https://github.com/loopj/android-smart-image-view

更新:我最终写了一个 有关此内容的博客文章,因此请查看它以获取有关使用 SmartImageView 的帮助。

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

Lots of good info in here...I recently found a class called SmartImageView that seems to be working really well so far. Very easy to incorporate and use.

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

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

UPDATE: I ended up writing a blog post about this, so check it out for help on using SmartImageView.

2ND UPDATE: I now always use Picasso for this (see above) and highly recommend it. :)

半仙 2024-09-02 09:36:48
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
imageView.setImageBitmap(BitmapFactory.decodeStream(imageUrl.openStream()));//try/catch IOException and MalformedURLException outside
梦中的蝴蝶 2024-09-02 09:36:48

这将帮助您...

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

This will help you...

Define imageview and load image into it .....

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

Then Define this method :

    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;
}
傲影 2024-09-02 09:36:48
    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);
    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);
仅此而已 2024-09-02 09:36:48

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

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

Version with exception handling and async task:

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();
}
叫思念不要吵 2024-09-02 09:36:48
    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;
    } 
    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;
    } 
高冷爸爸 2024-09-02 09:36:48

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

A simple and clean way to do this is to use the open source library Prime.

再浓的妆也掩不了殇 2024-09-02 09:36:48

适用于任何容器中的 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 );

Working for imageView in any container , like listview grid view , normal layout

 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 );
行雁书 2024-09-02 09:36:48

尝试这种方式,希望这能帮助您解决问题。

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

  • 从此处下载“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.

Try this way,hope this will help you to solve your problem.

Here I explain about how to use "AndroidQuery" external library for load image from url/server in asyncTask manner with also cache loaded image to device file or cache area.

  • Download "AndroidQuery" library from here
  • Copy/Paste this jar to project lib folder and add this library to project build-path
  • Now I show demo to how to use it.

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.
半窗疏影 2024-09-02 09:36:48

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

请查看此处

我认为是最好的方法。

Android Query can handle that for you and much more (like cache and loading progress).

Take a look at here.

I think is the best approach.

夜唯美灬不弃 2024-09-02 09:36:48

这段代码经过测试,完全可以工作。

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

This code is tested, it is completely working.

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());
不念旧人 2024-09-02 09:36:47

来自 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 中设置了以下访问互联网的权限。

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

From Android developer:

// 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.xml to access the internet.

<uses-permission android:name="android.permission.INTERNET" />
走野 2024-09-02 09:36:47

1. Picasso 可以轻松实现应用程序中的图像加载 — 通常只需一行代码!

使用 Gradle:

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

只需一行代码!

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

2. Glide 图像加载和缓存库适用于 Android,专注于平滑滚动

使用 Gradle:

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 入门

4. < a href="https://coil-kt.github.io/coil/" rel="noreferrer">Coil 是一个由 Kotlin 协程支持的 Android 图像加载库。

implementation("io.coil-kt:coil:2.3.0")

要将图像加载到 ImageView 中,请使用加载扩展函数:

imageView.load("https://example.com/image.jpg")

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

Use Gradle:

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

Just one line of code!

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

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

Use Gradle:

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 is a powerful system for displaying images on Android applications. Fresco takes care of image loading and display, so you don't have to.

Getting Started with Fresco

4. Coil is an image loading library for Android backed by Kotlin Coroutines.

implementation("io.coil-kt:coil:2.3.0")

To load an image into an ImageView, use the load extension function:

imageView.load("https://example.com/image.jpg")
相守太难 2024-09-02 09:36:47

您必须首先下载图像

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

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

梦醒灬来后我 2024-09-02 09:36:47

不管怎样,人们要求我发表评论作为答案。我正在发帖。

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

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);
被翻牌 2024-09-02 09:36:47

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

https://github.com/koush/UrlImageViewHelper

UrlImageViewHelper 将填充
ImageView 与找到的图像
位于 URL。

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

UrlImageViewHelper会自动
下载、保存和缓存所有
图像 url BitmapDrawables。
重复的网址不会被加载到
记忆两次。位图内存被管理
通过使用弱引用哈希表,
所以一旦图像不再
被你用了就会变成垃圾
自动收集。

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

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.

绾颜 2024-09-02 09:36:47

如果您根据按钮单击加载图像,上面接受的答案非常好,但是如果您在新活动中执行此操作,它会使 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);

结果是快速加载的活动和根据用户的网络速度稍后显示的图像视图。

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.

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:

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.

ゃ人海孤独症 2024-09-02 09:36:47

您还可以使用此 LoadingImageView 视图从以下网址加载图像:

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

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

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:

in 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");
依 靠 2024-09-02 09:36:47

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

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

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

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
迷鸟归林 2024-09-02 09:36:47

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

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

试试这个

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

等待我真够勒 2024-09-02 09:36:47
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;
}
}
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;
}
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文