I am writing this tutorial as lot of people are asking me about loading an image into imageview. Just by adding url to ImageView won’t load directly. Instead we need to store the image into cache (temporary location) and attach to ImageView. This can be achieved just by calling couple of lines and don’t forget to add required classes to your project.

Download Code

1. Create a new project in Eclipse IDE by navigating to File ⇒ New ⇒ Android Project and fill the required details.
2. Inorder to load images from an url we first need to store the image in a temporary location and once it is downloaded it should be added to ImageView. To create a temporary file we need to access device external storage. Add required permission to AndroidManifest.xml file.

To access internet required permission is – INTERNET
To access external storage required permission is – WRITE_EXTERNAL_STORAGE

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidhive.imagefromurl"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidLoadImageFromURLActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    
    <!-- Internet Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />
    
    <!-- Permission to write to external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

</manifest>

3. For testing purpose create a simple ImageView in your main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Loading image from url"
        android:layout_margin="10dip" />
    
    <ImageView android:id="@+id/image"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:layout_margin="10dip"/>

</LinearLayout>

4. Open your main activity and type the following code. Whenever you wan’t to show an image from url just call the following code.

imgLoader.DisplayImage(image_url, loader, image);
// image_url - is image url path
// loader - loader image, will be shown before loading image
// image - is ImageView
package com.androidhive.imagefromurl;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidLoadImageFromURLActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Loader image - will be shown before loading image
        int loader = R.drawable.loader;
        
        // Imageview to show
        ImageView image = (ImageView) findViewById(R.id.image);
        
        // Image url
        String image_url = "https://api.androidhive.info/images/sample.jpg";
        
        // ImageLoader class instance
        ImageLoader imgLoader = new ImageLoader(getApplicationContext());
        
        // whenever you want to load an image from url
        // call DisplayImage function
        // url - image url to load
        // loader - loader image, will be displayed before getting image
        // image - ImageView 
        imgLoader.DisplayImage(image_url, loader, image);
    }
}

5. Add following classes in your project and run the project.

Required Classes

ImageLoader.java

package com.androidhive.imagefromurl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
 
public class ImageLoader {
 
    MemoryCache memoryCache=new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService; 
 
    public ImageLoader(Context context){
        fileCache=new FileCache(context);
        executorService=Executors.newFixedThreadPool(5);
    }
 
    int stub_id = R.drawable.ic_launcher;
    public void DisplayImage(String url, int loader, ImageView imageView)
    {
    	stub_id = loader;
        imageViews.put(imageView, url);
        Bitmap bitmap=memoryCache.get(url);
        if(bitmap!=null)
            imageView.setImageBitmap(bitmap);
        else
        {
            queuePhoto(url, imageView);
            imageView.setImageResource(loader);
        }
    }
 
    private void queuePhoto(String url, ImageView imageView)
    {
        PhotoToLoad p=new PhotoToLoad(url, imageView);
        executorService.submit(new PhotosLoader(p));
    }
 
    private Bitmap getBitmap(String url)
    {
        File f=fileCache.getFile(url);
 
        //from SD cache
        Bitmap b = decodeFile(f);
        if(b!=null)
            return b;
 
        //from web
        try {
            Bitmap bitmap=null;
            URL imageUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setInstanceFollowRedirects(true);
            InputStream is=conn.getInputStream();
            OutputStream os = new FileOutputStream(f);
            Utils.CopyStream(is, os);
            os.close();
            bitmap = decodeFile(f);
            return bitmap;
        } catch (Exception ex){
           ex.printStackTrace();
           return null;
        }
    }
 
    //decodes image and scales it to reduce memory consumption
    private Bitmap decodeFile(File f){
        try {
            //decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f),null,o);
 
            //Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE=70;
            int width_tmp=o.outWidth, height_tmp=o.outHeight;
            int scale=1;
            while(true){
                if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                    break;
                width_tmp/=2;
                height_tmp/=2;
                scale*=2;
            }
 
            //decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize=scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {}
        return null;
    }
 
    //Task for the queue
    private class PhotoToLoad
    {
        public String url;
        public ImageView imageView;
        public PhotoToLoad(String u, ImageView i){
            url=u;
            imageView=i;
        }
    }
 
    class PhotosLoader implements Runnable {
        PhotoToLoad photoToLoad;
        PhotosLoader(PhotoToLoad photoToLoad){
            this.photoToLoad=photoToLoad;
        }
 
        @Override
        public void run() {
            if(imageViewReused(photoToLoad))
                return;
            Bitmap bmp=getBitmap(photoToLoad.url);
            memoryCache.put(photoToLoad.url, bmp);
            if(imageViewReused(photoToLoad))
                return;
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
        }
    }
 
    boolean imageViewReused(PhotoToLoad photoToLoad){
        String tag=imageViews.get(photoToLoad.imageView);
        if(tag==null || !tag.equals(photoToLoad.url))
            return true;
        return false;
    }
 
    //Used to display bitmap in the UI thread
    class BitmapDisplayer implements Runnable
    {
        Bitmap bitmap;
        PhotoToLoad photoToLoad;
        public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
        public void run()
        {
            if(imageViewReused(photoToLoad))
                return;
            if(bitmap!=null)
                photoToLoad.imageView.setImageBitmap(bitmap);
            else
                photoToLoad.imageView.setImageResource(stub_id);
        }
    }
 
    public void clearCache() {
        memoryCache.clear();
        fileCache.clear();
    }
 
}

FileCache.java

package com.androidhive.imagefromurl;

import java.io.File;
import android.content.Context;
 
public class FileCache {
 
    private File cacheDir;
 
    public FileCache(Context context){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"TempImages");
        else
            cacheDir=context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
 
    public File getFile(String url){
        String filename=String.valueOf(url.hashCode());
        File f = new File(cacheDir, filename);
        return f;
 
    }
 
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();
    }
 
}

MemoryCache.java

package com.androidhive.imagefromurl;

import java.lang.ref.SoftReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import android.graphics.Bitmap;
 
public class MemoryCache {
    private Map<String, SoftReference<Bitmap>> cache=Collections.synchronizedMap(new HashMap<String, SoftReference<Bitmap>>());
 
    public Bitmap get(String id){
        if(!cache.containsKey(id))
            return null;
        SoftReference<Bitmap> ref=cache.get(id);
        return ref.get();
    }
 
    public void put(String id, Bitmap bitmap){
        cache.put(id, new SoftReference<Bitmap>(bitmap));
    }
 
    public void clear() {
        cache.clear();
    }
}

Utils.java

package com.androidhive.imagefromurl;

import java.io.InputStream;
import java.io.OutputStream;
 
public class Utils {
    public static void CopyStream(InputStream is, OutputStream os)
    {
        final int buffer_size=1024;
        try
        {
            byte[] bytes=new byte[buffer_size];
            for(;;)
            {
              int count=is.read(bytes, 0, buffer_size);
              if(count==-1)
                  break;
              os.write(bytes, 0, count);
            }
        }
        catch(Exception ex){}
    }
}
This image is for thumbnail purpose
android loading image from url
Subscribe
Notify of
guest
240 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
m.k.
m.k.
8 years ago

hello, thank you for tutorial. Unfortunately, it works for me only on emulator and when i install it on my phone, images won’t load. Why does this happen?

m.k.
m.k.
8 years ago
Reply to  m.k.

and I need to tell that i have 83 mb of free memory on SD card and 50 mb free internal memory

Ajay Kumar
Ajay Kumar
8 years ago

Can Someone help me how can i integrate progressbar in this code? please!

arjun kn
arjun kn
8 years ago

realy thanks man… works fine…

David Dimalanta
David Dimalanta
8 years ago

There is a problem with the ImageLoader class. You see, when I added the BitmapFactory.Options o2 under decodeFile(File f) method, I get an “Unreachable Code” error status. What should I do?

Smart guy
Smart guy
8 years ago

no image will be show only loader image is shown help me whats the problem

David Dimalanta
David Dimalanta
8 years ago

Raise the REQUIRED_SIZE.

David Dimalanta
David Dimalanta
8 years ago

This tutorial is the worst! It is due by updates, instead of the image loaded properly from the URL, I got corrupted image as a result. Look at my sample.

http://stackoverflow.com/questions/14845878/corrupted-image-when-getting-imageviews-source-from-the-internet

Kimmi Dhingra
Kimmi Dhingra
8 years ago

hello..i have to load images & and data from webservices…can u plz help me….

Pratik Butani
7 years ago
Reply to  Kimmi Dhingra

this is what you want

waseem ahmad
waseem ahmad
7 years ago
Reply to  Pratik Butani

@pratik butani,,,,how to load info like(username ,intrest,gender ,,) in this code

subash
subash
8 years ago

u can use universal image loader library for that…………….

Dilip Panchal
Dilip Panchal
8 years ago

I want to display image in ListVIew From PHP Server or web server .
But I need to set my Enulator HeapSize more than 32 MB. It Generate Errors.
Can I Use Above Code to Display Image in List View From Server.
Help Me.
I am your website great FAN.

Dilip

Fernando
Fernando
8 years ago

Hi
this tutorial is so good
i read about a lib for developer games in android [libgdx]
can you do tutorials about this?

jaradat
jaradat
8 years ago

i want to show image in large size so i replace _s by _n but it save it as small,as follow:
String _n=_s.replace(“_s.jpg”, “_n.jpg”);
imageLoader2.DisplayImage(_n, picture);

plz could any one help me?

anonim
anonim
8 years ago

break the json into pices until you get the url

waseem ahmad
waseem ahmad
7 years ago
Reply to  anonim

@anonim …..plzzzz explain how to code to get (username ,…gender,…etc) i m also using json webservic url ,,,,aftr login

Rajsekar
Rajsekar
8 years ago

Hi Ravi
This tutorial is very helpful to me please post the dynamic grid view (Images from server) at least please give me a sugeestions

Poongkundran
Poongkundran
8 years ago

Please give me code to display multiple images from MYSQL DB with help of php webservice

DataBaseManager
DataBaseManager
7 years ago
Reply to  Poongkundran

DisplayFromDB();

Nirmal Revar
Nirmal Revar
8 years ago

hi did u got solution of that image blurred ,,,,

Khyati
Khyati
8 years ago

With the same code when i replace image url it throws FileNotFound Exception . i m stuck with it. Any idea?

avinash
avinash
7 years ago
Reply to  Khyati

check permissions

Abhishek garg
Abhishek garg
5 years ago
Reply to  avinash

sir i have same problem
and i have already add this permision

Chaitendra Pratap
Chaitendra Pratap
7 years ago

Thnaks this is very helpful..

Pratik Butani
7 years ago

Hi Ravi… Its Fantastic Tutorial.. Thanks a lot.

Here I want to Update Image directly in My Folder, how can i update without passing ImageVIew object.

i have tried like this:

new ImageLoader(this).getBitmap(imagePath);

It’s giving me Error…

what can i do… Please Reply me…

Urvish Shah
Urvish Shah
7 years ago

Hello sir i am getting too many redirects exception please help me out.

ishaque
ishaque
7 years ago

hi ravi …great tutorial ….thankz for this..

then can you provide the API php code for how can i add image to my database and retrieve from it and send to my android app using json…..

Miguel
Miguel
7 years ago

Hi Ravi, I haven’t tried this yet, but I want to know if I can use this for populating listview with images? Thanks!

waseem ahmad
waseem ahmad
7 years ago
Reply to  Ravi Tamada

hi ravi …can i also use this .code to show profile information(user name,intresrt,gender…user_image….) aftr login……..from the webservice

Guest
Guest
7 years ago

Hi Ravi,
How can i set size image from your project, image downloaded and show on device too small than this link:comment image
Thanks so much

njzk2
njzk2
7 years ago

That would be nicer if you actually wrote this code.

Amit
Amit
7 years ago

Hi, thanx for the good tutorial but i want to load multiple images ho to do that?

Vy.NLN
Vy.NLN
7 years ago

Pls help me out!
Why i use this link:comment image
above sample can’t load image, return bitmap=null;

Udhay
Udhay
7 years ago

Reading image from URL can be performed inside AsynTask as it should not affect the current Activity. Using AysnTask will run downloading image from URL as separate thread.
Regards,
Udhay
http://programmerguru.com

Ashish Tiwari
Ashish Tiwari
7 years ago

Hi, How to store the Images in internal memory of the phone? In this tutorial we are using External memory for cache

Dheeraj
Dheeraj
7 years ago

hi , The tutorial helped me a lot…

I have one question though.. Where can I change the size of the image which is downloaded?

Is it possible?

Thanks,

SBE
SBE
7 years ago

did not works with images in a listview

guytrx
guytrx
7 years ago

GREAT TUTORIAL i use it to my app – its work perfect!:)
i m asking your help guys
i use my personal String url – JSON that i downloads about 500 images from my Json!
when i scroll the list view fast i
MUST HAVE A SPINNER PROGRESS BAR IN EVERY ROW IN THE LIST VIEW UNTIL THE IMAGE SHOW/COMPLIT –
PLEASE HELP ME WITH THIS

Tom Bardsley
Tom Bardsley
7 years ago

hi. What is R.drawable.loader? I ask because my program does not recognize it

SSRI
SSRI
7 years ago
Reply to  Tom Bardsley

It is an image name exists in the drawable folder

Rajesh Narwal
Rajesh Narwal
7 years ago

Its working but i am unable to understand this code. It would be lot better if you explain the working of this project.
Thanks

SSRI
SSRI
7 years ago
Reply to  Rajesh Narwal

cvb

jayanti
jayanti
7 years ago

nice this is so good

Wilson
Wilson
7 years ago

Hi Ravi, where do i need to recycle the bitmap? im having trouble whenever i re-open my app using these codes. it says out of memory. thanks

Ej Castro
Ej Castro
7 years ago

Hi, may i know what is the R.drawable.loader. If it was a code/ image may i have it cause i dont have it on my drawable folder. Thanks in advance.

Ej Castro
Ej Castro
7 years ago
Reply to  Ej Castro

Got it, just an image.

Ej Castro
Ej Castro
7 years ago

Im using a fragment and this how i use it:

ImageLoader imgLoader = new ImageLoader(getActivity().getApplicationContext());

public void DisplayImage(String url, int loader, ImageView imageView)
{
stub_id = loader;
imageViews.put(imageView, url);
Bitmap bitmap=memoryCache.get(url);
if(bitmap!=null)
imageView.setImageBitmap(bitmap);
else
{
queuePhoto(url, imageView);
imageView.setImageResource(loader);
}
}
And im getting an error when i call the java class. What is the problem on my code?

Deepak
Deepak
7 years ago
Reply to  Ej Castro

only use

ImageLoader imgLoader = new ImageLoader(getActivity() );

waseem ahmad
waseem ahmad
7 years ago

hi ravi i want to know ….i want to set image in circle …i m using this code …..so whare to edit ..what to edit in code…..plzzzz rply fast

RedHood
RedHood
7 years ago

Very helpful, thanks

waseem ahmad
waseem ahmad
7 years ago

i ravi i m using this code its working i have i query ….i want to display image in size as i want …….can u tell me how to increse/decrease size of image which is comming from url

waseem ahmad
waseem ahmad
7 years ago

i ravi i m using this code its working i have i query ….i want to display image in size as i want …….can u tell me how to increse/decrease size of image which is comming from url….plzz reply fast

Droid Addict
7 years ago

What if I want to make the extension of string image_url automatically detect whether .jpg or .png?
// Image url
String image_url = “http://api.androidhive.info/images/sample.jpg”; // or png?

elleray
elleray
7 years ago

I’m confused with this function”boolean imageViewReused(PhotoToLoad photoToLoad)”,could you tell me what it is used for?

vahid
vahid
7 years ago

thank you very much. Many useful posts :-*

suraj
suraj
7 years ago

07-19 19:15:40.211: E/StrictMode(1106): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.

suraj
suraj
7 years ago

07-19 19:15:25.171: E/StrictMode(1085): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.

07-19 19:15:25.171: E/StrictMode(1085): java.lang.Throwable: Explicit termination method ‘end’ not called

07-19 19:15:25.171: E/StrictMode(1085): at dalvik.system.CloseGuard.open(CloseGuard.java:184)

07-19 19:15:25.171: E/StrictMode(1085): at java.util.zip.Inflater.(Inflater.java:82)

07-19 19:15:25.171: E/StrictMode(1085): at java.util.zip.GZIPInputStream.(GZIPInputStream.java:96)

07-19 19:15:25.171: E/StrictMode(1085): at java.util.zip.GZIPInputStream.(GZIPInputStream.java:81)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.okhttp.internal.http.HttpEngine.initContentStream(HttpEngine.java:610)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:856)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:347)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.okhttp.internal.http.HttpURLConnectionImpl.getHeaderField(HttpURLConnectionImpl.java:143)

07-19 19:15:25.171: E/StrictMode(1085): at java.net.URLConnection.getContentType(URLConnection.java:326)

07-19 19:15:25.171: E/StrictMode(1085): at java.net.URLConnection.getContent(URLConnection.java:193)

07-19 19:15:25.171: E/StrictMode(1085): at java.net.URL.getContent(URL.java:455)

07-19 19:15:25.171: E/StrictMode(1085): at com.example.marico.LibaryClass.loadImageFromWeb(LibaryClass.java:661)

07-19 19:15:25.171: E/StrictMode(1085): at com.example.marico.LibaryClass.onCreate(LibaryClass.java:251)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.Activity.performCreate(Activity.java:5426)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.ActivityThread.access$900(ActivityThread.java:161)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)

07-19 19:15:25.171: E/StrictMode(1085): at android.os.Handler.dispatchMessage(Handler.java:102)

07-19 19:15:25.171: E/StrictMode(1085): at android.os.Looper.loop(Looper.java:157)

07-19 19:15:25.171: E/StrictMode(1085): at android.app.ActivityThread.main(ActivityThread.java:5356)

07-19 19:15:25.171: E/StrictMode(1085): at java.lang.reflect.Method.invokeNative(Native Method)

07-19 19:15:25.171: E/StrictMode(1085): at java.lang.reflect.Method.invoke(Method.java:515)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)

07-19 19:15:25.171: E/StrictMode(1085): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)

07-19 19:15:25.171: E/StrictMode(1085): at dalvik.system.NativeStart.main(Native Method)

dhiraj choudhary
dhiraj choudhary
7 years ago

hi, ravi your tutorials are superb but how could i increase the size of cache for bigger image files or higher resolution bitmaps

Ravi Tamada
7 years ago

Ignore this tutorial. Now the better way to load image is using Volley library.
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
(check 8. Making Image request)

Anshul Goyal
Anshul Goyal
7 years ago

I also wanted to load images from android phone(internal and external storage) but this image loader download image from http request. How may do it with using internal and external storage.

Wahib
Wahib
6 years ago

Hi, I followed this tutorial for my app. I populate a listview from an api. Each item of my listview has an image.
After loading a certain amount of image i encounter a
java.lang.OutOfMemoryError: pthread_create (stack size 16384 bytes) failed: Try again

How can I avoid that?

Thanks in advance.

Er B S Choudhary
Er B S Choudhary
6 years ago

lot of thanks to androidhive.info….

240
0
Would love your thoughts, please comment.x
()
x