1

I have Multiple images on the server. What I want to do is I want to retrieve these images from the server and set it on the imageView.

I have worked with getting the blob type images from the server, decoding it to byte array and then convert it to Bitmap images.

I am confused about how to get Bitmap images from the server.

I have been through many questions on SO like

Retriving image from server to android app

Load Large Image from server on Android

Please can any one help with a Link or a code.

Thank You for your precious time.

I was trying things and here is the code:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Bitmap bitmap = DownloadImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");


    ImageView img = (ImageView) findViewById(R.id.img);
    img.setImageBitmap(bitmap);
}

private InputStream OpenHttpConnection(String urlString) 
throws IOException
{
    InputStream in = null;
    int response = -1;

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection();

    if (!(conn instanceof HttpURLConnection))                     
        throw new IOException("Not an HTTP connection");

    try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();                 
        if (response == HttpURLConnection.HTTP_OK) {
            in = httpConn.getInputStream();                                 
        }                     
    }
    catch (Exception ex)
    {
        throw new IOException("Error connecting");            
    }
    return in;     
}
private Bitmap DownloadImage(String URL)
{        
    Bitmap bitmap = null;
    InputStream in = null;   



    try {
        in = OpenHttpConnection(URL);
        BufferedInputStream bis = new BufferedInputStream(in, 8190);

        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        System.out.println("BAF= "+baf);
        int current = 0;
        while ((current = bis.read()) != -1) 
        {
            baf.append((byte)current);
        }
        byte[] imageData = baf.toByteArray();
        System.out.println("imageData= "+imageData);
        bitmap =BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
        in.close();
    } 
   catch (IOException e1) 
   {

        e1.printStackTrace();
    }
    return bitmap;                
}
}

This returns the image but he url that i have used consists of the image name. What if i have more images and I want to retrieve all of the them as my application loads.

Community
  • 1
  • 1
Droid
  • 419
  • 4
  • 15
  • check this tutorial about how to download an image from server asynchronously using AsyncTask : http://www.android-ios-tutorials.com/182/show-progressbar-while-downloading-image-using-asynctask-in-android/ – Houcine Oct 11 '13 at 08:44
  • 2
    volley, picasso, prime ... – njzk2 Oct 11 '13 at 09:02
  • Thank you all for your answers. But everyone suggesting a different technique and i am new to all these ,which has confused me more. – Droid Oct 11 '13 at 09:16

5 Answers5

5

I recommend you a different way that works like a charm: Android Query.

You can download that jar file from here: http://code.google.com/p/android-query/downloads/list

AQuery androidAQuery=new AQuery(this);

As an example:

androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);

Using above code you can directly show your Image through url. Now below code is to get Bitmap Directly from the url:

androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
                        @Override
                        public void callback(String url, Bitmap object, AjaxStatus status) {
                            super.callback(url, object, status);

                            //You will get Bitmap from object.
                        }


  });

This library is provided by Android itself, so use it and see the result whatever you want.

It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.

Hardik
  • 17,179
  • 2
  • 35
  • 40
Pratik Dasa
  • 7,439
  • 4
  • 30
  • 44
  • ok try it nad if this post is helpful to you then please accept and upvote so other people can use this. – Pratik Dasa Oct 11 '13 at 08:59
  • The link you provided consists of various jar files. Should I download all of them or there is any specific one. – Droid Oct 11 '13 at 09:00
  • No do only one, the first one or second one only. – Pratik Dasa Oct 11 '13 at 09:01
  • hey i have updated my question. can you plz tell me what is required more with the code. – Droid Oct 11 '13 at 09:24
  • 1
    Whatever images you want to get, get all your url's at a time and store them in array or arraylist, then using loop do work with Android Query. So one by one your images will be downloaded and displayed. – Pratik Dasa Oct 11 '13 at 09:28
3

I would recommend you use the Volley library (The presentation is here), the same library used by Google in its application Google Play. At the Google I/O 13, Ficus Kilkpatrick presented Volley. Volley is an HTTP library that aims at removing lots of boilerplate code, simplifying the handling of images in lists, be faster, abstract the complexity of one or another HTTP client.

Initialization

Volley relies on a RequestQueue, that handle a queue of request, and on an ImageLoader, that is in charge of loading the images. We need one of each

public static ImageLoader mImageLoader;
public static RequestQueue mRequestQueue;

We also need to initialize them. The queue needs a Context, the ImageLoader needs an ImageCache. Here, I use a basic wrapper to LruCache.

mRequestQueue = Volley.newRequestQueue(this);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLru(64000));

The initialization is done in the onCreate() of the first activity.

Getting an image

Suppose you have to fill a gridview with images downloaded from a server. The ImageUrlAdapter populates a GridView (or any AdapterView) with NetworkImageView. This is a class provided by Volley to put images from the network into an ImageView. It actually extends ImageView, meaning you can use it anywhere you use an ImageView. It is extremely simple to use. The only code in the adapter is the getView.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    NetworkImageView imageView;
    if (convertView == null) {
        imageView = new NetworkImageView(getContext());
    } else {
        imageView = (NetworkImageView) convertView;
    }
    String url = getItem(position);
    imageView.setImageUrl(url, MainActivity.mImageLoader);
    return imageView;
}

The only new thing here is imageView.setImageUrl(url, MainActivity.mImageLoader);

That’s it. Nothing more is required.

Diego Palomar
  • 6,958
  • 2
  • 31
  • 42
  • hey i have being going through the video. Can i also retrieve .zip file from the server using this? – Droid Oct 11 '13 at 09:29
  • What you have to do is clone the project repository (git clone https://android.googlesource.com/platform/frameworks/volley) and import inside your IDE as Android library and finally from your project make a reference to the imported project in order to use it. – Diego Palomar Oct 11 '13 at 09:42
2

Use the Universal Image Loader

Since your confused I'll explain

Download the jar file by clicking here and paste it into your libs folder

In your manifest add these two lines of permission

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

Use this code

ImageLoader imageLoader = ImageLoader.getInstance();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.createDefault(getApplicationContext())
imageLoader.init(config);
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.ic_launcher)
.cacheInMemory()
.cacheOnDisc()
.build();
imageLoader.displayImage("http://www.allindiaflorist.com/imgs/arrangemen4.jpg",your_IMAGEVIEW,options,null);

Or if you just want the bitmap then use this

Bitmap bmp = imageLoader.loadImageSync("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
Girish Nair
  • 5,148
  • 5
  • 40
  • 61
1

I would strongly recommend using the Square's Picasso library. It's very easy to work with and takes away all the pain of retrieving-caching.

linakis
  • 1,203
  • 10
  • 19
0

I would suggest using Prime Library , it has functioning to download images asynchronously and then a callback with a listener having the url and bitmap image as the parameters.

Shubhank
  • 21,721
  • 8
  • 65
  • 83