I'm successfully storing logged in user info like user name user email and other important information in shared preferences. But I'm looking for the best way to store the user's image.
Asked
Active
Viewed 19 times
1 Answers
0
You can still use sharedpreference since you store other information in shared preference too. All you have to do is, convert your image to it's Base64
string representation:
Bitmap realImage = BitmapFactory.decodeStream(stream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
realImage.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
textEncode.setText(encodedImage);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("image_data",encodedImage);
edit.commit();
and then, when retrieving, convert it back into bitmap:
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");
if( !previouslyEncodedImage.equalsIgnoreCase("") ){
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
imageConvertResult.setImageBitmap(bitmap);
}
However, I have to tell you that Base64 support is only recently included in API8. To target on lower API version, you need to add it first. Luckily, this guy already have the needed tutorial.
There is a quick and dirty example on github.
Original Thread here.
Hope it helps!

Angus
- 3,680
- 1
- 12
- 27