178

I have an image URL. I want to display an image from this URL in an ImageView but I am unable to do that.

How can this be achieved?

MasterScrat
  • 7,090
  • 14
  • 48
  • 80
Sanat Pandey
  • 2,599
  • 5
  • 28
  • 40
  • 1
    Possible duplicate of [How to load an ImageView by URL in Android?](http://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android) – blahdiblah Apr 16 '12 at 19:54
  • 1
    you can use Picasso and Glide image loader and displayed to imageview – shweta c Jun 30 '16 at 10:31
  • 1
    look these questions and focus at the first answers, here you can find two simple and complete ways to do this: [first method (more complete)](https://stackoverflow.com/questions/2471935/how-to-load-an-imageview-by-url-in-android) or [second method (more simply)](https://stackoverflow.com/questions/3118691/android-make-an-image-at-a-url-equal-to-imageviews-image) – lory105 Jul 24 '12 at 13:02

17 Answers17

330

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

Dont forget to add below permission in your manifest file

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

Works great for me. :)

King of Masses
  • 18,405
  • 4
  • 60
  • 77
Kyle Clegg
  • 38,547
  • 26
  • 130
  • 141
268
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Adrian Frühwirth
  • 42,970
  • 10
  • 60
  • 71
Rajath
  • 11,787
  • 7
  • 48
  • 62
  • 65
    You really ought to not to use that, as it blocks the UI thread. This library will handle threading and downloading for you: https://github.com/koush/UrlImageViewHelper – koush Aug 24 '12 at 04:49
  • 16
    Not if u run that block on a seperate thread minus the setImageBitmap – Jono Jan 17 '13 at 15:40
  • its working i displaying in thumbnails and onclick imageview i used dsplaying dailog but it opens after 10secs – Prasad Sep 16 '14 at 13:02
  • 4
    @koush - This code would be fine if wrapped in an `AsyncTask`. – Greg Brown Jul 22 '16 at 13:18
  • 2
    You should make any networl operations in a separate thread, When bitmap has been loaded, you could use ImageView.post() or Handler.post() – Volodymyr Shalashenko Jun 06 '17 at 11:43
  • Just a note that method call BitmapFactory.decodeStream(url.openConnection().getInputStream()) on main thread or inside runOnUIThread() will cause android.os.NetworkOnMainThreadException. I've used same code, but I've created new thread and run it inside them and it's working fine. Setting bitmap image on image view needs to be implemented inside runOnUIThread() – dkero Feb 12 '22 at 16:37
45

try picasso nice and finishes in one statement

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

tutorial: https://youtu.be/DxRqxsEPc2s

(note: Picasso.with() has been renamed to Picasso.get() in the latest release)

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
vijaicv
  • 535
  • 5
  • 9
  • 3
    Picasso, Glide are my favorites, also. The statement of Glide is quite similar to Picasso, with much improvement in cache size. – anhtuannd Mar 08 '16 at 06:20
  • 1
    This should be the new answer, although its always nice to know how to do it on your own. Great article explaining both ways: https://medium.com/@crossphd/android-image-loading-from-a-string-url-6c8290b82c5e – Martin Jäkel Feb 22 '19 at 09:43
  • for loading url which is better Picasso or Glide in terms of performance? – Prajwal Waingankar Aug 22 '20 at 22:44
11

There are two ways:

1) Using Glide library This is the best way to load an image from a URL because when you try to display the same URL the second time it will display from the cache so improving app performance

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

dependency : implementation 'com.github.bumptech.glide:glide:4.10.0'


2) Using Stream Here you want to create a bitmap from a URL image

URL url = new URL("YourUrl");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bitmap);
Sweta Jain
  • 3,248
  • 6
  • 30
  • 50
Sanjayrajsinh
  • 15,014
  • 7
  • 73
  • 78
9

Try this add picasso lib jar file

Picasso.with(context)
                .load(ImageURL)
                .resize(width,height).noFade().into(imageView);
Rakesh Rangani
  • 1,039
  • 10
  • 13
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();
        }


    }


}

in your activity take imageview & set resource imageDownload(url,yourImageview);

6

Based on this answer i write my own loader.

With Loading effect and Appear effect :

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

Add permission

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

And execute :

 new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();
Community
  • 1
  • 1
Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
5

UrlImageViewHelper will fill an ImageView with an image that is found at a URL. 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.

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

https://github.com/koush/UrlImageViewHelper

koush
  • 2,972
  • 28
  • 31
5

add Internet permission in manifest

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

than create methode as below,

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

now add this in your onCreate method,

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


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

this is works for me.

Jinal Awaiya
  • 441
  • 3
  • 14
4

Here is sample code for display Image from 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();
        }
    }
Niranj Patel
  • 32,980
  • 10
  • 97
  • 133
3

Best Method I have tried instead of using any libraries

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;
    }
}
Sabari Karthik
  • 184
  • 3
  • 8
  • 24
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);
        }
    }
}
Rahul Raina
  • 3,322
  • 25
  • 30
2

The code below show you how to set ImageView from a url string, using RxAndroid. First, add RxAndroid library 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'

}

now use setImageFromUrl to set image.

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);
            }
        });
}
DàChún
  • 4,751
  • 1
  • 36
  • 39
1
loadImage("http://relinjose.com/directory/filename.png");

Here you go

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
    }
}
Exceptional
  • 2,994
  • 1
  • 18
  • 25
1

Try this:

InputStream input = contentResolver.openInputStream(httpuri);
Bitmap b = BitmapFactory.decodeStream(input, null, options);
slavoo
  • 5,798
  • 64
  • 37
  • 39
chung
  • 11
  • 1
1

To me, Fresco is the best among the other Libraries.

Just setup Fresco and then simply set the ImageURI like this:

draweeView.setImageURI(uri);

Check out this answer explaining some of Fresco Benefits.

Mr_Milky
  • 155
  • 9
Wilder Pereira
  • 2,249
  • 3
  • 21
  • 31
0

This is my working solution using Adrian's code example:

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

Note: You can use this pre-defined method to load image bitmap or you can use yours in case you need to resize image or some similar operation over image.

dkero
  • 121
  • 1
  • 8