Parsing Image from Internet



  • If you want to get an image from internet and use it in your android application, here are some very simple steps to do the job.
  • Step 1- Create a variable of class InputStream and initialize it to null.

    InputStream is=null;


    Step 2- Download the content of a url in the variable created above.

    try {

    is = (InputStream) new URL(url).getContent();

    } catch (MalformedURLException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    } catch (IOException e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }


  • Here, URL is the constructor of class of URL which takes a String as its only parameter. This string is nothing but the url of the image. You may use following url to test the app.
  • http://www.eitworld.com/eitlogo.png

  • The method 'getContent()' downloads the complete content from the url. The url that you will use must only contain an image.
  • Note: The try- catch block is must because the constructor 'ULR()' always throws an exception. Now we are having the content in variable of InputStream.
  • Step 3- Get the image from this InputStream variable in the form of drawable. The method 'creteFromStream(InputStream,srcName)' does this job. Its first parameter is the InputStream that contains the image and second parameter is a String for 'src name' which can be anything that you like.

    Drawable draw = Drawable.createFromStream(is, "image name");


    Step 4- Now this drawable can be used anywhere according to your need. For example you may display it in an ImageView.

    imageview.setImageDrawable(draw);


    Step 5- Use following code in onCreate() method.

    StrictMode.ThreadPolicy policy = new StrictMode.

    ThreadPolicy.Builder().permitAll().build();

    StrictMode.setThreadPolicy(policy);


  • StrictMode is there to inform you that you might be doing something accidently. By writing above code, we are saying that everything we are doing here is deliberately. In other words, we have got the permission for parsing the image.
  • Step 6- Give the permission to access internet in AndroidManifest.xml file.

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