Saturday, January 26, 2008

I needed to load remote images to my application and bind this image to an ImageView object. HttpURLConnection is used to download the image data and BitmapFactory is used to produce the bitmap which will be used as imageview resources.

Here is the layout file

XML:

< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
< TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HTTPImage load test"
/>
< Button id="@+id/get_imagebt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get an image"
android:layout_gravity="center"
/>
< ImageView id="@+id/imview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
< /LinearLayout>


The java code goes like it


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class HTTPTest extends Activity {


ImageView imView;
String imageUrl="http://11.0.6.23/";
Random r;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
r= new Random();

Button bt3= (Button)findViewById(R.id.get_imagebt);
bt3.setOnClickListener(getImgListener);
imView = (ImageView)findViewById(R.id.imview);
}

View.OnClickListener getImgListener = new View.OnClickListener()
{

@Override
public void onClick(View view) {
// TODO Auto-generated method stub

//i tried to randomize the file download, in my server i put 4 files with name like
//png0.png, png1.png, png2.png so different file is downloaded in button press
int i =r.nextInt()%4;
downloadFile(imageUrl+"png"+i+".png");
Log.i("im url",imageUrl+"png"+i+".png");
}

};


Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
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();

bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


The code is pretty simple and easy, most of you might already have done this, i am a slow learner, i tried different ways first, i tried to read the whole bytes of image data, do other trial and error method. I was confused about the Bitmap tranformation technology. Then i found that there is a built in class known as BitmapFactory, it can produce bitmap directly from stream. This saved a lot of my efforts. Hope it will come useful to you.

Happy andcoding :)

17 Comments:

  1. Dogbert Rulez said...
    Hi Shimul,
    I need help with your post on
    http://getablogger.blogspot.com/2007/06/j2me-custom-item.html

    What I want to know is how you managed to enter TEXT in the CustomItem. How did you enable Predictive input and MultiTap for the custom item. Please help me as I have been stuck on this for some time now!!!
    Dogbert Rulez said...
    Please contact me at [dogbertrulez]ATgmailDOTcom
    John Weiss said...
    Thank-you for providing examples. I am struck immediately, by the the words I'm a slow learner. It encourages us REALLY Slow Learners to keep on plugging away.
    Anonymous said...
    Good Stuff, Very Useful! Thanks.
    Janusz L. said...
    Thanks for the example.
    In you code are old parts from the earlier attempts to read the image bytewise I think. The two variables bitMapData and bitMapData2 are unused.
    Bhupesh said...
    Hi this bhupesh,
    the code above is very helpful can anyone help me to break an image. I mean i am working on jigsaw puzzle application so need to create a matrix of image pieces.

    Thank you
    bhupesh.nagda18@gmail.com is my Email-id
    assaf passal said...
    Crash on my nexus one, any idea?
    assaf passal said...
    my mistake, work great thank you very much
    Jereme said...
    impressive. so how do I store it as an image file?
    Anonymous said...
    hey i want to display image into email body and the image was selected form sdcard(Android in built gallery) is this possible?
    Anshul Upadhyay said...
    THanx it was very helpful.
    many thnx!
    Sergo Don said...
    You can also find here - http://android-apps-blog.blogspot.com/2011/04/how-to-load-image-from-web-on-android.html a tutorial on How to load image from web on Android
    KenGorab said...
    Hi, I'm a slow learner at this stuff as well but I have a question—what is the significance of the bitmapData and bitmapData2 arrays, as I don't see them referenced elsewhere in the code.
    krishna kanth said...
    Ur Code for Bitmap Image is not working the bmp object is returning Null please help me .... I can download any image from net via android device except bitmap .... kindly help me yaar
    Froggie said...
    Thank you :). This worked well. Some lines of code aren't needed though from what I've found.

    I squashed it into this and it seemed to work fine:

    private Bitmap downloadFile(String fileUrl){

    Bitmap bmImg = null;
    URL myFileUrl =null;

    try {

    myFileUrl= new URL(fileUrl);

    HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
    conn.setDoInput(true);
    conn.connect();
    InputStream is = conn.getInputStream();

    bmImg = BitmapFactory.decodeStream(is);

    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    return bmImg;

    }
    Anonymous said...
    I absolutely admired account your blog. It was actual able-bodied authored and accessible to understand. Unlike added blogs I accept apprehend which absolutely not that are good. I additionally begin your posts actual interesting. In actuality afterwards reading, I had to go appearance it to my acquaintance and he enjoyed it as well!

    Android app developer
    EZFrag said...
    Hi guys,

    I found an excellent class for android which both downloads and caches downloaded images.

    http://theandroidcoder.com/utilities/android-image-download-and-caching/

    The guy seems to be struggling to add some kind of expiration date to the cached items though, but overall it is very good.

    Regards,
    EZFrag

Post a Comment