Converting Image URL to Bitmap

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,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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!
 

posted on   veins  阅读(207)  评论(0编辑  收藏  举报

努力加载评论中...

导航

点击右上角即可分享
微信分享提示