Droid
Droid

Reputation: 419

Getting Bitmap images from server to set on ImageView

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.

Upvotes: 1

Views: 9835

Answers (5)

Pratik Dasa
Pratik Dasa

Reputation: 7439

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.

Upvotes: 5

Girish Nair
Girish Nair

Reputation: 5216

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

Upvotes: 2

linakis
linakis

Reputation: 1231

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.

Upvotes: 1

Diego Palomar
Diego Palomar

Reputation: 7061

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.

Upvotes: 3

Shubhank
Shubhank

Reputation: 21805

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.

Upvotes: 0

Related Questions