How to Download an image in ANDROID programatically?

By | July 7, 2011

Hello everyone..
In one of my tutorials I have shown you how to upload an image in android..
In todays tutorial I will show you how to download an image into your phone programatically.
I am just picking up an image url from google to show the download.

Previously I have shown three other methods to upload files to a server.
Check these posts to refer this.

1. Uploading audio, video or image files from Android to server
2. How to Upload Multiple files in one request along with other string parameters in android?
3. ANDROID – Upload an image to a server.

This is the main program that downloads the file.

package pack.coderzheaven;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class DownloadImage extends Activity {

	private final String PATH = "/data/data/pack.coderzheaven/";
	TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView)findViewById(R.id.tv);
        DownloadFromUrl(PATH+"dwn_img.jpg");
    }
    public void DownloadFromUrl(String fileName) {
            try {
                    URL url = new URL("http://t3.gstatic.com/images?q=tbn:ANd9GcQs0EPegqi56Alq4vCgC_lVDbZvJtk51RhER7AyDEVA3nUkzjMVK-yDHY3V-w"); //you can write here any link
                    File file = new File(fileName);

                    long startTime = System.currentTimeMillis();
                    tv.setText("Starting download......from " + url);
                    URLConnection ucon = url.openConnection();
                    InputStream is = ucon.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    /*
                     * Read bytes to the Buffer until there is nothing more to read(-1).
                     */
                    ByteArrayBuffer baf = new ByteArrayBuffer(50);
                    int current = 0;
                    while ((current = bis.read()) != -1) {
                            baf.append((byte) current);
                    }

                    FileOutputStream fos = new FileOutputStream(file);
                    fos.write(baf.toByteArray());
                    fos.close();
                    tv.setText("Download Completed in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
            } catch (IOException e) {
            	 tv.setText("Error: " + e);
            }
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">

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


    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".DownloadImage"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">DownloadImage Demo from CoderzHeaven</string>
    <string name="app_name">DownloadImage</string>
</resources>
Download Image Demo

Download Image Demo

Download Image Demo

Download Image Demo

18 thoughts on “How to Download an image in ANDROID programatically?

  1. Pingback: Link to How to Download an image in ANDROID programatically? | Coderz Heaven

  2. limo

    well cool stuff and only people who would be able to do this are programmers, so what would you advice for non-programmers as myself!!

    Reply
  3. Android Applications Development

    Thanks for sharing in details about “how to upload an image in android”.This will be very useful for the Android users.

    Reply
  4. ishan

    how to populate a list view with images on my sqlite database
    (using image paths from sdcard)

    Reply
    1. James Post author

      ishan : We only reply to people who are there in our Facebook or twitter Fan club. Sorry…

      Reply
  5. kien

    I don’t run the program.I wrote than you
    It recieve the “try catch” as soom as the program runs

    Reply
  6. Mateus

    Hi Dear! Excellent job!
    I’m trying download files 2, 3 and 8MB each (many files…). When I type on adb shell ls -l, all files has been listed, but, all the same size :-S. Can you help me?

    Reply
    1. James Post author

      Hi Mateus:- Recheck your code, this will not happen, Are you downloading the same file with different names. Open the images and see.

      Reply
  7. LamprosGk

    Hi, I want to download all images that exist in a specific folder in my server, do I a need server-side/php script also or can I do that only with java in my app code?

    Reply
    1. James Post author

      NO need of a php script actually but you need to know the URL of the images in your server.
      OR another way is write a php script to send the URLs and get it on the android side then start downloading images one by one.

      Reply
      1. LamprosGk

        thanks James.
        so the use of a server-side script is only to get the URLs, the transfer gets done by java right?
        Assuming i know the URLs, there’s no need of script.

        (forgive me for my not so good english :p)

        Reply
        1. James Post author

          yes, java can do the download, check this post and replace with your image URL.IF you know the image URLs then there is no need of the script.

          Reply
  8. Jimsonmok

    Besides download an image, how to download an audio from server to an android phone?

    Reply
    1. James Post author

      Hello Jimsonmok:-
      Downloading an audio file is same as downloading an image file, just the extension changes.

      Reply
  9. Pingback: Download Image From URL in Android « tediscript.wordpress.com

  10. sheelu

    When the code is copied and executed..
    there was an error occuring.. the field tv missing in R.id..

    How to edit this??

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *