-1

I'm making a user profile which the user can change his profile picture, but I want the selected image to be stored and not to disappear after I go to another activity, I already did the selecting image from the gallery part. I know this has something to do with shared preferences or bitmap coding but I can't seem to figure out how to do it.

How can I do that exactly, and thank you.

Eefret
  • 4,724
  • 4
  • 30
  • 46
Akram
  • 1
  • 1

1 Answers1

0

First covert the Image Path you get into Base64 String using this function

public static String getFileToByte(String path){
  Bitmap bm = null;
  ByteArrayOutputStream baos = null;
  byte[] b = null;
  String encodeString = null;
   try{
    bm = BitmapFactory.decodeFile(path);
    baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    b = baos.toByteArray();
    encodeString = Base64.encodeToString(b, Base64.DEFAULT);
  }catch (Exception e){
    e.printStackTrace();
  }
  return encodeString;
 }

Save the Base64 in SharedPreferences

    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
Editor edit=shre.edit();
edit.putString("image_data",getFileToByte("/path/to/image.jpg"));
edit.commit();

Show it back in IMAGEVIEW when needed

    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);
    imageView.setImageBitmap(bitmap);
    }
jagapathi
  • 1,635
  • 1
  • 19
  • 32