Load ImageView with bitmap from internet

It's a simple way to load ImageView with a bitmap from internet, via http connection.

Load ImageView with bitmap from internet

In order to load something from internet, the AndroidManifest.xml have to be modified to grand permission for internet access.

package="com.exercise.AndroidWebImage"
android:versionCode="1"
android:versionName="1.0">

android:label="@string/app_name">












Modify main.xml to include a ImageView

android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
android:id="@+id/image"
android:scaleType="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>



java code:
package com.exercise.AndroidWebImage;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;

public class AndroidWebImage extends Activity {

String image_URL=
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgt-PXliYdaHrZj3fxAqPQ4Ka-pH9S-wJl7dwzIb2iF0yXpwfSv5QK9zkEkMZ_C_-rvvCQWHOOzPBP7lOBWLzp9gpI2zQE_ofuTIJOPWrEabGVtq1AEkwAmpdNY16kDemv3jyhWhEPlvnKx/s1600-r/android.png";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ImageView bmImage = (ImageView)findViewById(R.id.image);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
bmImage.setImageBitmap(bm);
}

private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}

private InputStream OpenHttpConnection(String strURL) throws IOException{
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();

try{
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();

if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}
catch (Exception ex)
{
}
return inputStream;
}

}


Post a Comment

Previous Post Next Post

Contact Form