Android decode image from url


An image downloaded from the internet might be bigger than your phone's screen size. It takes up the memory unnecessarily. So, to load the image effectively in a container (e.g. ImageView), you have to decode it. In this Android tip, I am going to show you how to read and decode an image from a URL.
To read an image from the URL, you can use the HttpURLConnection class to connect and get an InputStream object from a remote server. The InputStream object will be passed to the decodeStream() method of BitmapFactory class to be decoded. This process can take much time. To read and decode the image from the internet without locking the user interface, this process should be placed in a background thread. The AsyncTask class helps you to handle this thing.
Now to have an example application on decoding an image from a URL, you create an Android project. Then add a TextView and an ImageView to the activity_main.xml file.


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context="com.example.andexample.MainActivity" >

   <TextView
     android:id="@+id/txtstatus"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
    
     />
  <ImageView
     android:id="@+id/imgview"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_above="@+id/txtstatus"
    
     />

</RelativeLayout>


Here is the code written in the MainActivity class to download an image from a URL, decode the image, and display it in the ImageView.

package com.example.andexample;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

int screenWidth;
int screenHeight;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     DisplayMetrics metrics=new DisplayMetrics();
     // Get screen size (width and height)
     this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
     screenWidth=metrics.widthPixels;
     screenHeight=metrics.heightPixels;
     BackTask bt=new BackTask();
     bt.execute("http://upload.wikimedia.org/wikipedia/commons/5/51/Small_Red_Rose.JPG");
   }
  

// AsynnTask to run download and decode an image in background
   private class BackTask extends AsyncTask<String,Void,Bitmap>{
   TextView txtstatus;
   ImageView imgview;
   protected void onPreExecute(){
   txtstatus=(TextView)findViewById(R.id.txtstatus);
   imgview=(ImageView)findViewById(R.id.imgview);    
   txtstatus.setText("Downloading and decoding the image. Please wait...");
   }
   protected Bitmap doInBackground(String...params){
  
   // Decode image (without loading it in memory) to get its size
   // The size will be used to calculate a sample size used in decode the image
   final BitmapFactory.Options options = new BitmapFactory.Options();  
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeStream(getInputStream(params[0]), null, options);
   int imgHeight = options.outHeight;
   int imgWidth = options.outWidth;
   // Default sample size
   int sampleSize=1;
   // Calculate the sample size
   if(screenWidth< imgWidth || screenHeight<imgHeight ){
   int widthRatio=Math.round(imgWidth/(float)screenWidth);
   int heightRatio=Math.round(imgHeight/(float)screenHeight);
   sampleSize=Math.round((widthRatio+heightRatio)/(float)2);
  
   }
  
   // Decode the image with the specified sample size
   options.inJustDecodeBounds = false;
   options.inSampleSize=sampleSize;
   Bitmap bitmap=BitmapFactory.decodeStream(getInputStream(params[0]), null, options);
   return bitmap;

   }
   protected void onPostExecute(Bitmap result){
   // Hide the status text
   txtstatus.setVisibility(TextView.GONE);
   imgview.setImageBitmap(result);
   }
  
   }
  
   private InputStream getInputStream(String address){

   try {
   // Get InputStream from the image url
   URL url = new URL(address);
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   connection.setDoInput(true);
   connection.connect();
   return connection.getInputStream();
   }
   catch(IOException e){
   return null;
   }
   }

  
}


Reading data from the internet requires internet permission. So, before you run the application, you have to add the internet permission to the AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>

Android-decode-image-from-url

Posted by: Dara | post date: 11-14-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.