从URL加载图片

178

我有一个图片的URL,想要在ImageView中显示这张图片,但我无法做到。

如何实现这个功能呢?


1
可能是如何在Android中通过URL加载ImageView?的重复问题。 - blahdiblah
1
看看这些问题,重点关注第一个答案,你可以在这里找到两种简单完整的方法来实现:第一种方法(更完整)第二种方法(更简单) - lory105
1
你可以使用Picasso和Glide图像加载器,并将其显示到ImageView上。 - shweta c
17个回答

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

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

AsyncTask已被弃用。 - Bokili Production
@BokiliProduction 这段代码是在2015年发布的推荐实践。现在这个API已经被弃用了。 - Rahul Raina
好的,我只是在评论有些人不会深入研究不必要的浪费时间。比AsyncTask更简单和更快的解决方案有很多。我向你致敬,我的朋友。 - Bokili Production

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

1

对我来说,Fresco 是其他库中最好的。

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

draweeView.setImageURI(uri);

请查看this的答案,解释了一些Fresco的好处。


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 是什么? - Big McLargeHuge
XML 设计中 ImageView 使用的 ID。 - Exceptional

1

试试这个:

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

0
这是我使用Adrian的代码示例得出的工作解决方案:
private void loadImage(String pUrl) {
    Thread imageDataThread = new Thread(() -> {
        try {
            URL tUrl = new URL(pUrl);
            Bitmap imageBitmap = BitmapFactory.decodeStream(tUrl.openConnection().getInputStream());
            runOnUiThread(() -> image_preview.setImageBitmap(imageBitmap));
        } catch(IOException pExc) {
            showToast("Error loading image for this question!");
            pExc.printStackTrace();
        }
    });
    imageDataThread.start();
}

注意:您可以使用此预定义方法来加载图像位图,或者如果您需要调整图像大小或对图像进行某些类似操作,则可以使用自己的方法。

什么是image_preview? - Kheersagar patel
这是一个ImageView。 - dkero

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