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

android, image, sharedpreferences

Solution

I solved your problem do something like that:

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;
}

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();

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);
}

Please pass your string inside this method and do what you want.

Problem

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.

Original source

Related problems