Search code examples
javaandroidimageviewsharedpreferencesonactivityresult

Android: How do I save an ImageView to SharedPreferences for save and retrieve?


I am creating an application and am currently wondering how do I save an image to SharedPreferences, and then retrieve that same image, please see below the code I have regarding the Images. What do I need to add to this?

 public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    // Checks if the intent was able to pick the image and if it was successful
    if(requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null){

        // Get selected image uri from phone gallery
        Uri selectedImage = data.getData();

        // Display selected photo in image view
        imageView.setImageURI(selectedImage);
    }

    // Handle Camera Request
    else if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK && data != null){

        // Bitmap variable to store data
        Bitmap bitmap = (Bitmap)data.getExtras().get("data");

        // Display taken picture in image view
        imageView.setImageBitmap(bitmap);
    }


    else if (requestCode == GALLERY_REQUEST_AFTER && resultCode == RESULT_OK && data != null){

        Uri selectedImageAfter = data.getData();

        imageView2.setImageURI(selectedImageAfter);
    }

    else if (requestCode == CAMERA_REQUEST_AFTER && resultCode == RESULT_OK && data != null){

        Bitmap bitmapAfter = (Bitmap)data.getExtras().get("data");

        imageView2.setImageBitmap(bitmapAfter);
    }
}

Solution

  • If you want to save and restore the Bitmap associated to the ImageView, you can save a Base64 encoding of this Bitmap in the SharedPreferences.

    Here is an example,

    //get SharedPreferences
    private static final String PREF_BITMAP_KEY = "PREF_BITMAP_KEY";
    SharedPreferences prefs = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    
    //get Bitmap and Base64 encoding
    Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    
    byte[] bytes = baos.toByteArray();
    String b64 = Base64.encodeToString(bytes, Base64.DEFAULT);
    
    //save in SharedPreference
    prefs.edit().putString(PREF_BITMAP_KEY, b64);
    prefs.edit().commit();
    

    To restore the Bitmap:

    String b64 = prefs.getString(PREF_BITMAP_KEY, null); 
    if (!TextUtils.isNullOrEmpty(b64)) {
      byte[] bytes = Base64.decode(b64, Base64.DEFAULT);
      Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
      imageView.setImageBitmap(bitmap);
    }