download image from url to sdcard

download the image from url to sd card in android

download the image from URL to sd card in android

In this tutorial, I am going to explain How to download the image from URL and store the image into sd card directly.

Steps to Download the Image from URL to sd card

  1. To download the image we need to have an internet connection. So that First, we need to add Internet Permission in our Application Manifest.xml
    <uses-permission android:name=”android.permission.INTERNET”></uses-permission>
    <uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”></uses-permission>The permission model/workflow has been changed from API 23 – Android M. So we need to get the permission at runtime.

    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
    }
  2. Get the image URL.
  3. Create Async Task to load the image from URL in the background. Basically, Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive.
    class myAsyncTask extends AsyncTask<Void, Void, Void> {
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }
    
        @Override
        protected Void doInBackground(Void... voids) {
            return null;
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }
    }
  4. In Async Task doInBackground(), create Http GET request and download the image from URL.
    URL url = new URL(imageURL);
     //create the new connection
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    //set up some things on the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
    //and connect!
    urlConnection.connect();
  5. Use Environment.getExternalStorageDirectory() to get the Root Directory of the sd card.
     File SDCardRoot = Environment.getExternalStorageDirectory();
  6. FileOutputStream() –   used to write the downloaded data into the file we created.
    FileOutputStream fileOutput = new FileOutputStream(file);
  7. Read the data from the internet using

    urlConnection.getInputStream()

    method.
    InputStream inputStream = urlConnection.getInputStream();
  8. Create buffer and read through the input buffer and write the contents to the file.
    byte[] buffer = new byte[1024];
    int bufferLength = 0; //used to store a temporary size of the buffer
    //now, read through the input buffer and write the contents to the file
    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
        //add the data in the buffer to the file in the file output stream (the file on the sd card
        fileOutput.write(buffer, 0, bufferLength);
        //add up the size so we know how much is downloaded
        downloadedSize += bufferLength;
        //this is where you would do something to report the prgress, like this maybe
        //updateProgress(downloadedSize, totalSize);
    }
  9. Finally, close the output stream when done.
    fileOutput.close();
  10. To check the download image, Please go to sd card folder on your device. If you are using device emulator, Go to Device File Explorer and check under sd card folder.
    check downloaded image in sd card

Download the Image from URL to sd card Example

MainActivity.Java

public class MainActivity extends AppCompatActivity {

    String imageURL ="http://35.200.174.74/images/home/velmm_icon.png";
    private static final int EXTERNAL_STORAGE_PERMISSION_CONSTANT = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
        }
    }

    public void downloadImageFromUrl(View view){
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this,"No Permission",Toast.LENGTH_SHORT).show();
        } else {
            MyAsyncTask asyncTask = new MyAsyncTask();
            asyncTask.execute();
        }
    }

    class MyAsyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                URL url = new URL(imageURL);
                 //create the new connection
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                //set up some things on the connection
                urlConnection.setRequestMethod("GET");
                urlConnection.setDoOutput(true);
                //and connect!
                urlConnection.connect();
                //set the path where we want to save the file in this case, going to save it on the root directory of the sd card.
                File SDCardRoot = Environment.getExternalStorageDirectory();
                //create a new file, specifying the path, and the filename which we want to save the file as.
                File file = new File(SDCardRoot,"image.jpg");
                //this will be used to write the downloaded data into the file we created
                FileOutputStream fileOutput = new FileOutputStream(file);
                //this will be used in reading the data from the internet
                InputStream inputStream = urlConnection.getInputStream();
                //this is the total size of the file
                int totalSize = urlConnection.getContentLength();
                //variable to store total downloaded bytes
                int downloadedSize = 0;
                byte[] buffer = new byte[1024];
                int bufferLength = 0; //used to store a temporary size of the buffer
                //now, read through the input buffer and write the contents to the file
                while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    //add the data in the buffer to the file in the file output stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    //add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    //this is where you would do something to report the prgress, like this maybe
                    //updateProgress(downloadedSize, totalSize);
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }
        return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            Toast.makeText(getApplicationContext(),"Image Downloaded to sd card",Toast.LENGTH_SHORT).show();
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.velmurugan.downloadimagefromurl.MainActivity">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="downloadImageFromUrl"
        android:text="Download Image to Sd card"/>
</LinearLayout>

velmm download code

1 thought on - download the image from url to sd card in android

  • Is your image downloading with this code?

Leave a Reply

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