How to save Image in shared preference in Android | Shared preference issue in Android with Image

In my application after login I have to save user name and image in shared preference for other pages. I am able to save name in preference but can't get any where how to save image.

I am trying something like that-

SharedPreferences myPrefrence;
    String namePreferance="name";

    String imagePreferance="image";

SharedPreferences.Editor editor = myPrefrence.edit();
                editor.putString("namePreferance", itemNAme);
                editor.putString("imagePreferance", itemImagePreferance);
                editor.commit();

I am trying to save image as string after convert it into object. But when I reconvert it into bitmap I did not get anything.


I solved your problem do something like that:

  1. Write Method to encode your bitmap into string base64-

    // method for bitmap to base64
    public static String encodeTobase64(Bitmap image) {
        Bitmap immage = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        immage.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
    
        Log.d("Image Log:", imageEncoded);
        return imageEncoded;
    }
    
  2. Pass your bitmap inside this method like something in your preference:

    SharedPreferences.Editor editor = myPrefrence.edit();
    editor.putString("namePreferance", itemNAme);
    editor.putString("imagePreferance", encodeTobase64(yourbitmap));
    editor.commit();
    
  3. And when you want to display your image just anywhere, convert it into a bitmap again using the decode method:

    // method for base64 to bitmap
    public static Bitmap decodeBase64(String input) {
        byte[] decodedByte = Base64.decode(input, 0);
        return BitmapFactory
                .decodeByteArray(decodedByte, 0, decodedByte.length);
    }
    
  4. Please pass your string inside this method and do what you want.


Finally I solved this problem.

Step:- 1. I wrote some code in onCreate() for get intent data from previous Activity

 private  Bitmap bitmap;

 Intent intent = getIntent();

        if (getIntent().getExtras() != null)
        {
            // for get data from intent

            bitmap = intent.getParcelableExtra("PRODUCT_PHOTO");

            // for set this picture to imageview

            your_imageView.setImageBitmap(bitmap);

             sharedPreferences();

        }else
        {
            retrivesharedPreferences();
        }

2 create sharedPreferences() and put this code

 private void sharedPreferences()
    {
        SharedPreferences shared = getSharedPreferences("App_settings", MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("PRODUCT_PHOTO", encodeTobase64(bitmap));
        editor.commit();
    }

3 create retrivesharedPreferences() this method and put this code,

private void retrivesharedPreferences()
    {
      SharedPreferences shared = getSharedPreferences("MyApp_Settings", MODE_PRIVATE);
        String photo = shared.getString("PRODUCT_PHOTO", "photo");
        assert photo != null;
        if(!photo.equals("photo"))
        {
            byte[] b = Base64.decode(photo, Base64.DEFAULT);
            InputStream is = new ByteArrayInputStream(b);
            bitmap = BitmapFactory.decodeStream(is);
            your_imageview.setImageBitmap(bitmap);
        }

    }

4 Write encodeTobase64() Method to encode your bitmap into string base64- and put code in this method

 public static String encodeTobase64(Bitmap image) {
        Bitmap bitmap_image = image;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap_image.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] b = baos.toByteArray();
        String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);

        return imageEncoded;
    }

I hope it will helpful for you.


Encode to Base64?! That's crazy talk! That's way too much information that you are storing to the shared preferences. The strategy you should be doing is saving the Image URI file path, and retrieving it as such. This way, your app won't be storing so much information and become a memory hog when decoding the image.

I made a simple App on Github to demonstrate this idea, if you want to follow:

1. Declare the variables:

private ImageView mImage;
private Uri mImageUri;

2. Select the image:

public void imageSelect() {
     Intent intent;
     if (Build.VERSION.SDK_INT < 19) {
         intent = new Intent(Intent.ACTION_GET_CONTENT);
     } else {
         intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
         intent.addCategory(Intent.CATEGORY_OPENABLE);
     }
     intent.setType("image/*");
     startActivityForResult(Intent.createChooser(intent, "Select Picture"),
         PICK_IMAGE_REQUEST);
 }

3. Save the image URI:

@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     // Check which request we're responding to
     if (requestCode == PICK_IMAGE_REQUEST) {
         // Make sure the request was successful
         if (resultCode == RESULT_OK) {
             // The user picked a image.
             // The Intent's data Uri identifies which item was selected.
            if (data != null) {

                // This is the key line item, URI specifies the name of the data
                mImageUri = data.getData();

                // Removes Uri Permission so that when you restart the device, it will be allowed to reload. 
                this.grantUriPermission(this.getPackageName(), mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                final int takeFlags = Intent.FLAG_GRANT_READ_URI_PERMISSION;
                this.getContentResolver().takePersistableUriPermission(mImageUri, takeFlags);

                // Saves image URI as string to Default Shared Preferences
                SharedPreferences preferences = 
                     PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("image", String.valueOf(mImageUri));
                editor.commit();

                // Sets the ImageView with the Image URI
                mImage.setImageURI(mImageUri);
                mImage.invalidate();
             }
         }
     }
 }

4. Retrieve the image URI when needed:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String mImageUri = preferences.getString("image", null);
mImage.setImageURI(Uri.parse(mImageUri));

That's it! Now we have saved the image uri path to shared preferences cleanly, and have not wasted valuable system resources encoding the image and saving it to SharedPreferences.