Android download and save image internally

1. Before downloading the image, let’s write a method for saving bitmap into an image file in the internal storage in android. It needs a context, better to use the pass in the application context by getApplicationContext(). This method can be dumped into your Activity class or other util classes.

public void saveImage(Context context, Bitmap b, String imageName) {
    FileOutputStream foStream;
    try {
        foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
        b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
        foStream.close();
    } catch (Exception e) {
        Log.d("saveImage", "Exception 2, Something went wrong!");
        e.printStackTrace();
    }
}

2. Now we have a method to save bitmap into an image file in andorid, let’s write the AsyncTask for downloading images by url. This private class need to be placed in your Activity class as a subclass. After the image is downloaded, in the onPostExecute method, it calls the saveImage method defined above to save the image. Note, the image name is hardcoded as “my_image.png”.

private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    private String TAG = "DownloadImage";
    private Bitmap downloadImageBitmap(String sUrl) {
        Bitmap bitmap = null;
        try {
            InputStream inputStream = new URL(sUrl).openStream();   // Download Image from URL
            bitmap = BitmapFactory.decodeStream(inputStream);       // Decode Bitmap
            inputStream.close();
        } catch (Exception e) {
            Log.d(TAG, "Exception 1, Something went wrong!");
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        return downloadImageBitmap(params[0]);
    }

    protected void onPostExecute(Bitmap result) {
        saveImage(getApplicationContext(), result, "my_image.png");
    }
}

3. The AsyncTask for downloading the image is defined, but we need to execute it in order to run that AsyncTask. To do so, write this line in your onCreate method in your Activity class, or in an onClick method of a button or other places you see fit.

new DownloadImage().execute("http://developer.android.com/images/activity_lifecycle.png");

4. After the image is downloaded, we need a way to load the image bitmap from the internal storage, so we can use it. Let’s write the method for loading the image bitmap. This method takes two paramethers, a context and an image file name, without the full path, the context.openFileInput(imageName) will look up the file at the save directory when this file name was saved in the above saveImage method.

public Bitmap loadImageBitmap(Context context, String imageName) {
    Bitmap bitmap = null;
    FileInputStream fiStream;
    try {
        fiStream    = context.openFileInput(imageName);
        bitmap      = BitmapFactory.decodeStream(fiStream);
        fiStream.close();
    } catch (Exception e) {
        Log.d("saveImage", "Exception 3, Something went wrong!");
        e.printStackTrace();
    }
    return bitmap;
}

5. Now we have everything we needed for setting the image of an ImageView or any other Views that you like to use the image on. When we save the image, we hardcoded the image name as “my_image.jpeg”, now we can pass this image name to the above loadImageBitmap method to get the bitmap and set it to an ImageView.

someImageView.setImageBitmap(loadImageBitmap(getApplicationContext(), "my_image.jpeg"));

6. To get the image full path by image name.

File file            = getApplicationContext().getFileStreamPath("my_image.jpeg");
String imageFullPath = file.getAbsolutePath();

7. Check if the image file exists.

File file            = getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.exists()) Log.d("file", "my_image.jpeg exists!");

8. To delete the image file.

File file            = getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.delete()) Log.d("file", "my_image.jpeg deleted!");

9. The image should be saved in /data/data/your.app.packagename/files/my_image.jpeg, check this post for accessing this directory from your device.

Search within Codexpedia

Custom Search

Search the entire web

Custom Search