Free Shipping

Secure Payment

easy returns

24/7 support

  • Home
  • Blog
  • How to Load Image from URL in ImageView in Android

How to Load Image from URL in ImageView in Android

 July 14  | 0 Comments

If you want to load an image from your web URL into Android ImageView in your android application, This blog is for you.
This blog gives you a step by step guide to display image from URL with source code for Android Studio.
These are all the steps to create a project in Android Studio.
Step 1.
Open Android Studio and Crate a project named as “ImageFromURL” and click Next.Step 2.
Select “Phone and Tablet” Option and click Next.Step 4 :
Create a new Blank activity as “MainActivity” and click Finish.Step 5:
Add Image code to activity_main.xml

<ImageView android:id="@+id/image"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_margin="10dip"/>

Step 6:

Image URL : String image_url = "https://acadgild.com/images/android-new.png";

Add Code to MainAcvtivity.java for Get Image from Web using BitMap:

try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}

Step 7:
Decodes Image and Scales it to reduce memory consumption
Add decodeFile() to MainActivity.java class..

private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}

Step 8 :
Add Intenet Permission to AndroidManifest.xml

<uses-permission android:name = “android.permission.INTERNET” />

Step 9 : Run Your Project .
Step 10 : You will get your output like below:Keep visiting  www.acadgild.com for more updates on Android and other technologies. Also learn how to store image in database by reading the next post.

>