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

前端 未结 4 644
难免孤独
难免孤独 2020-11-27 17:34

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 s

4条回答
  •  北海茫月
    2020-11-27 17:58

    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.

提交回复
热议问题