Android Studio Examples

100+ tutorials, source code, and examples to help you develop creative and technical skills.

How to save image to external storage android studio

AndroidManifest.xml

<!-- Add Read and Write Permissions in the Manifest File-->
    <uses-permission
        android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        tools:ignore="ScopedStorage" />

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/your_image" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/saveBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Save Image To Memory" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:adjustViewBounds="true" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/getImageBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Get Image From Memory" />
</LinearLayout>

MainActivity.java

import android.Manifest;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {

    private ImageView imageView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final AppCompatButton saveBtn = findViewById(R.id.saveBtn);
        final AppCompatButton getImageBtn = findViewById(R.id.getImageBtn);
        final ImageView imageView = findViewById(R.id.imageView);
        imageView2 = findViewById(R.id.imageView2);

        saveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // check if external storage permissions granted or not
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
                        ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                    // request for permissions
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 102);
                    }
                }
                else{
                    // getting bitmap from ImageView
                    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

                    // saving Bitmap to Memory
                    saveBitmapToMemory("file_name.jpg", bitmap); 
                }
            }
        });

        getImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getImageFromMemory("file_name.jpg");
            }
        });

    }

    private void saveBitmapToMemory(String filename, Bitmap bitmap) {

        OutputStream imageOutStream;

        try {

            // The latest and best way to save images into external storage above API level 29
            // In old methods, you can create your own folders in external storage's root directory to save file but now you are now unable to create folders in the root.
            // You can only use existing folder like Documents, Downloads, Pictures, Movies etc.
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DISPLAY_NAME, filename); // set image filename
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); // setting image file format
                values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES); // specify directory in which image will be saved

                //values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/YourFolderName"); // You can create your folder in Pictures Directory

                // getting uri or file location
                final Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

                // getting output stream to save file
                imageOutStream = getContentResolver().openOutputStream(uri);

            } else {

                // for below API level 29 we need to use old way to store Media Files like images, videos, etc.
                final String picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
                final File image = new File(picturesDirectory, filename);
                imageOutStream = new FileOutputStream(image);
            }

            // saving Bitmap
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageOutStream);
            imageOutStream.close(); //  close output stream
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something went wrong!! Unable to save Image " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void getImageFromMemory(String filename) {

        // specify image directory
        final File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        final File imageFile = new File(pictureDirectory, filename);

        // check if Image File Exists
        if (imageFile.exists()) {
            // getting bitmap from file
            final Bitmap fileBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());

            // setting Bitmap to ImageView
            imageView2.setImageBitmap(fileBitmap);
        } else {
            Toast.makeText(this, "File Not Exists", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 102) {
            if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "Permissions Declined", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Projects with Source Code + Video Tutorials

You can download our Java and Android Studio Projects with Source Code and Video Tutorials.

Simple-Calculator-App-for-Android------------------
----------
Simple Calculator App for Android
HD-Wallpaper-App-in-Android-Studio-----------
HD Wallpaper App in Android Studio
Online-Tic-Tac-Toe-game-Using-Firebase-Database-in-Android-Studio
Online Tic Tac Toe game Using Firebase Database in Android Studio

If you have any Questions or Queries
You can mail us at info.learnoset@gmail.com

Follow us to learn Coding and get in touch with new Technologies.