从网址加载图片


155

我有图片网址。我想在ImageView中显示来自此URL的图像,但是我无法做到这一点。

如何做到这一点?



查看这些问题并将重点放在第一个答案上,在这里您可以找到两种简单而完整的方法:第一种方法(更完整)第二种方法(更简单)
lory105

您可以使用Picasso和Glide图像加载器并显示到imageview
shweta c

Answers:


239
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);

60
您确实不应该使用它,因为它会阻塞UI线程。该库将处理线程和下载你: github.com/koush/UrlImageViewHelper
koush

16
如果您在减去setImageBitmap的单独线程上运行该块,则不会这样
Jonathan

它的工作我显示在缩略图和onclick imageview中,我使用了dsplaying dailog,但是它在10秒后打开
Prasad

4
@koush-如果将这些代码包装在AsyncTask
格雷格·布朗

2
您应该在单独的线程中进行任何networl操作,加载位图后,可以使用ImageView.post()或Handler.post()
Volodymyr Shalashenko

311

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

要在活动结束时使用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);

不要忘记在清单文件中添加以下权限

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

对我来说很棒。:)


2
我喜欢这种解决方案,您应该只清理onPostExecute的代码,因为它的内容已耗尽。
索菲娅2012年

这很棒。@Sofija您的清理是什么意思?如果图片数量未知怎么办?
2013年

@ 5er我的原始答案中有些括号不合适。此后,我已经清理了它,因此您应该可以按原样使用它。
凯尔·克莱格

别忘了我们还需要在清单中添加权限:<uses-permission android:name =“ android.permission.INTERNET” />
mike20132013 2014年

1
对于学习/黑客(推荐)来说,这真是太棒了,但是对于任何生产,您都应该使用Imageloader库,那里有很多东西。我最喜欢的是Universal Image loader,Picasso等
。– AmeyaB

31

一口气尝试picassso并完成

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).into(imageView);

教程:https//youtu.be/DxRqxsEPc2s


3
毕加索,格莱德也是我的最爱。Glide的陈述与Picasso非常相似,但缓存大小有了很大的改善。
anhtuannd

1
这应该是一个新的答案,尽管总是很高兴知道自己如何做。:伟大的文章,解释这两种方式 medium.com/@crossphd/...
马丁Jäkel


7
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;

public class imageDownload {

    Bitmap bmImg;
    void downloadfile(String fileurl,ImageView img)
    {
        URL myfileurl =null;
        try
        {
            myfileurl= new URL(fileurl);

        }
        catch (MalformedURLException e)
        {

            e.printStackTrace();
        }

        try
        {
            HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            int length = conn.getContentLength();
            int[] bitmapData =new int[length];
            byte[] bitmapData2 =new byte[length];
            InputStream is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();

            bmImg = BitmapFactory.decodeStream(is,null,options);

            img.setImageBitmap(bmImg);

            //dialog.dismiss();
            } 
        catch(IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
//          Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
        }


    }


}

在您的活动中,使用imageview并设置资源imageDownload(url,yourImageview);


5

UrlImageViewHelper将使用在URL处找到的图像填充ImageView。UrlImageViewHelper将自动下载,保存和缓存BitmapDrawables的所有图像URL。重复的网址不会两次加载到内存中。位图内存是通过使用弱引用哈希表来管理的,因此一旦您不再使用该图像,就会自动对其进行垃圾回收。

UrlImageViewHelper.setUrlDrawable(imageView,“ http://example.com/image.png”);

https://github.com/koush/UrlImageViewHelper


4

基于此答案,我编写了自己的加载程序。

具有加载效果和外观效果:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.InputStream;

/**
 * Created by Sergey Shustikov (pandarium.shustikov@gmail.com) at 2015.
 */
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
    public static final int ANIMATION_DURATION = 250;
    private final ImageView mDestination, mFakeForError;
    private final String mUrl;
    private final ProgressBar mProgressBar;
    private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {

        }

        @Override
        public void onAnimationEnd(Animation animation)
        {
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {

        }
    };
    private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {
            if (isBitmapSet)
                mDestination.setVisibility(View.VISIBLE);
            else
                mFakeForError.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animation animation)
        {

        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {

        }
    };
    private boolean isBitmapSet;

    public DownloadImageTask(Context context, ImageView destination, String url)
    {
        mDestination = destination;
        mUrl = url;
        ViewGroup parent = (ViewGroup) destination.getParent();
        mFakeForError = new ImageView(context);
        destination.setVisibility(View.GONE);
        FrameLayout layout = new FrameLayout(context);
        mProgressBar = new ProgressBar(context);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        mProgressBar.setLayoutParams(params);
        FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        copy.gravity = Gravity.CENTER;
        copy.width = dpToPx(48);
        copy.height = dpToPx(48);
        mFakeForError.setLayoutParams(copy);
        mFakeForError.setVisibility(View.GONE);
        mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
        layout.addView(mProgressBar);
        layout.addView(mFakeForError);
        mProgressBar.setIndeterminate(true);
        parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

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

    protected void onPostExecute(Bitmap result)
    {
        AlphaAnimation in = new AlphaAnimation(0f, 1f);
        AlphaAnimation out = new AlphaAnimation(1f, 0f);
        in.setDuration(ANIMATION_DURATION * 2);
        out.setDuration(ANIMATION_DURATION);
        out.setAnimationListener(mOutAnimationListener);
        in.setAnimationListener(mInAnimationListener);
        in.setStartOffset(ANIMATION_DURATION);
        if (result != null) {
            mDestination.setImageBitmap(result);
            isBitmapSet = true;
            mDestination.startAnimation(in);
        } else {
            mFakeForError.startAnimation(in);
        }
        mProgressBar.startAnimation(out);
    }
    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
}

添加权限

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

并执行:

 new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();

4

这是显示来自URL的图像的示例代码。

public static Void downloadfile(String fileurl, ImageView img) {
        Bitmap bmImg = null;
        URL myfileurl = null;
        try {
            myfileurl = new URL(fileurl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) myfileurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            int length = conn.getContentLength();
            if (length > 0) {
                int[] bitmapData = new int[length];
                byte[] bitmapData2 = new byte[length];
                InputStream is = conn.getInputStream();
                bmImg = BitmapFactory.decodeStream(is);
                img.setImageBitmap(bmImg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

3

我尝试过的最佳方法,而不使用任何库

public Bitmap getbmpfromURL(String surl){
    try {
        URL url = new URL(surl);
        HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
        urlcon.setDoInput(true);
        urlcon.connect();
        InputStream in = urlcon.getInputStream();
        Bitmap mIcon = BitmapFactory.decodeStream(in);
        return  mIcon;
    } catch (Exception e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
        return null;
    }
}

3

在清单中添加Internet权限

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

比创建方法如下

 public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src", src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap", "returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception", e.getMessage());
        return null;
    }
}

现在将其添加到您的onCreate方法中,

 ImageView img_add = (ImageView) findViewById(R.id.img_add);


img_add.setImageBitmap(getBitmapFromURL("http://www.deepanelango.me/wpcontent/uploads/2017/06/noyyal1.jpg"));

这对我有用。


2

下面的代码向您展示如何使用RxAndroid从URL字符串设置ImageView。首先,添加RxAndroid库2.0

dependencies {
    // RxAndroid
    compile 'io.reactivex.rxjava2:rxandroid:2.0.0'
    compile 'io.reactivex.rxjava2:rxjava:2.0.0'

    // Utilities
    compile 'org.apache.commons:commons-lang3:3.5'

}

现在使用setImageFromUrl设置图像。

public void setImageFromUrl(final ImageView imageView, final String urlString) {

    Observable.just(urlString)
        .filter(new Predicate<String>() {
            @Override public boolean test(String url) throws Exception {
                return StringUtils.isNotBlank(url);
            }
        })
        .map(new Function<String, Drawable>() {
            @Override public Drawable apply(String s) throws Exception {
                URL url = null;
                try {
                    url = new URL(s);
                    return Drawable.createFromStream((InputStream) url.getContent(), "profile");
                } catch (final IOException ex) {
                    return null;
                }
            }
        })
        .filter(new Predicate<Drawable>() {
            @Override public boolean test(Drawable drawable) throws Exception {
                return drawable != null;
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Consumer<Drawable>() {
            @Override public void accept(Drawable drawable) throws Exception {
                imageView.setImageDrawable(drawable);
            }
        });
}

2

有两种方法:

1)使用Glide库这是从url加载图像的最佳方法,因为当您尝试第二次显示相同的url时,它将从catch中显示,从而提高应用程序性能

Glide.with(context).load("YourUrl").into(imageView);

依赖关系: implementation 'com.github.bumptech.glide:glide:4.10.0'


2)使用流。在这里,您想从网址图片创建位图

URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);

1
loadImage("http://relinjose.com/directory/filename.png");

干得好

void loadImage(String image_location) {
    URL imageURL = null;
    if (image_location != null) {
        try {
            imageURL = new URL(image_location);         
            HttpURLConnection connection = (HttpURLConnection) imageURL
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            bitmap = BitmapFactory.decodeStream(inputStream);// Convert to bitmap
            ivdpfirst.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        //set any default
    }
}

什么ivdpfirst
大麦克拉格巨大

xml设计中使用的ImageView的ID。
出色的

1

试试这个:

InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);

1
public class MainActivity extends Activity {

    Bitmap b;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView1);
        information info = new information();
        info.execute("");
    }

    public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected String doInBackground(String... arg0) {

            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){}
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            img.setImageBitmap(b);
        }
    }
}

1

对我而言,壁画是其他图书馆中最好的。

只需设置 Fresco,然后像这样简单地设置imageURI:

draweeView.setImageURI(uri);

查看答案,解释壁画的一些好处。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.