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 form URL with source code for Android Studio.
These are the all 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 on Next.
Step 3:
Add an activity as a Blank Activity and click on Next.
Step 4 :
Create a new Blank activity as “MainActivity” and click Finish.
Step 5:
Add Image code to activity_main.xml
1 2 3 4 |
<ImageView android:id="@+id/image" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_margin="10dip"/> |
Step 6:
1 |
Image URL : String image_url = "https://acadgild.com/images/android-new.png"; |
Add Code to MainAcvtivity.java for Get Image from Web using BitMap:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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; } |
1 2 3 4 5 6 7 |
//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
1 |
<uses-permission android:name = “android.permission.INTERNET” /> |
Step 9 : Run Your Project .
Step 10 : You will get your output like below:
Leave a Reply