how can I save an ImageView in sharedpreferences? I am trying to create a quiz where the player needs coins to unlock the next level, so the next level will be with a lock, and as soon as the player buys the level, the lock goes away, I already got the score. save, now only the image is missing, thanks in advance everyone!
-
1Does this answer your question? [How to save Image in shared preference in Android | Shared preference issue in Android with Image](https://stackoverflow.com/questions/18072448/how-to-save-image-in-shared-preference-in-android-shared-preference-issue-in-a) – Kanzariya Hitesh Jan 04 '20 at 05:51
3 Answers
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);
ret
urn 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);
}
Please pass your string inside this method and do what you want.

- 220
- 3
- 10
Get bitmap from the imageview then convert into base64 string then save it to the sharedpreference then again when you need the image get the base64 string convert to bitmap then user imageview.setBitmap(bitmap);
Now You are all set
For encoding and decoding bitmap you can use this, :
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;
}
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory
.decodeByteArray(decodedByte, 0, decodedByte.length);
}

- 13
- 5
It isn't a good idea to store your images in shared preferences because shared preferences are used for storing app settings that are lightweight. You should use an SQLite or Room database especially if you have many images. Another way is to cache your images in external storage.

- 189
- 1
- 10

- 1,073
- 7
- 18