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

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.

Leave a Comment