Skip to content

Converting Image URL to Bitmap

December 25, 2009

Hey everyone,

This post is for anyone who has ever wanted to load an image from a given URL and turn it into a Bitmap which you can then use to set as an ImageView’s background, or upload as a Contact’s photo, etc.

So here it is,

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
Nothing too complicated – simply create a URL object using the “src” string (i.e. String src = “http://thinkandroid.wordpress.com”), connect to it, and use Android’s BitmapFactory class to decode the input stream. The result should be your desired Bitmap object!
- jwei
About these ads
8 Comments leave one →
  1. January 3, 2011 2:52 pm

    Thanks! Question: If I wanted to get the contact photo URL for SDK Level 3 (Android 1.5 – yes, 1.5), how would I do _that_?

  2. October 24, 2011 10:44 am

    You could also open the Stream via the openStream Method of the URl object. Or is there a reason you shouldn’t do it that way?

  3. December 19, 2012 2:01 pm

    I’m not that much of a internet reader to be honest
    but your sites really nice, keep it up! I’ll go ahead and bookmark your site to come back later on. Many thanks

  4. December 19, 2012 6:29 pm

    Right here is the right blog for everyone who hopes to find out
    about this topic. You realize a whole lot its almost hard to argue with you (not that I actually would want to…HaHa).

    You definitely put a brand new spin on a topic that has been written about for ages.
    Wonderful stuff, just wonderful!

  5. Sergio permalink
    January 8, 2013 1:48 pm

    Thanks a lot
    Thats what I was looking for

Trackbacks

  1. Think Android
  2. Google App Engine – Bringing it Back To Android (4) « Think Android
  3. Lazy Loading Images: From URLs to ListViews « Think Android

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 896 other followers

%d bloggers like this: