在android中从URL加载Bitmap到ImageView

时间:2015-05-11 19:43:07

标签: android url bitmap bitmapfactory

我正在使用以下方法从网址中检索位图并将其传递给imageview,但是图片视图没有更新。

 public static Bitmap LoadImageFromWebOperations(String url) {
    Bitmap bitmap;
    try {
        InputStream is = new URL(url).openStream();
       bitmap = BitmapFactory.decodeStream(is);
        return bitmap;
    } catch (Exception e) {
         return null;
    }

致电 -

  mov1_poster.setImageBitmap(VPmovies.LoadImageFromWebOperations(mov_details[0][7]));
//doesn't work

  Toast.makeText(this,"url is \n"+mov_details[0][7],Toast.LENGTH_LONG).show();
   // shows the url of the image successfully (just to check the url is not null)

我有什么问题吗?请帮忙。

2 个答案:

答案 0 :(得分:7)

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    private ImageView imageView;
    private Bitmap image;

    public DownloadImageTask(ImageView imageView) {
        this.imageView = imageView;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            image = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            image = null;
        }
        return image;
    }

    @SuppressLint("NewApi")
    protected void onPostExecute(Bitmap result) {
        if (result != null) {
            imageView.setImageBitmap(result);
        }
    }
}

现在请致电您的代码:

 new DownloadImageTask(YOUR_IMAGE_VIEW).execute("YOUR_URL");

答案 1 :(得分:1)

使用the picasso library处理图片时,它可以创造奇迹,而且很简单!

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