Xamarin.Android:使用共享首选项将图像永久保存为个人资料图片

Xamarin.Android: Save a Image permanently like a profile picture with Shared Preferences

在我的 Xamarin.Android 应用程序中,我想要封面图片之类的东西,它会在应用程序第一次启动时保存。用户可以通过单击示例图片来更改它。

到目前为止一切顺利,但是当我关闭应用程序并重新启动时,图片没有显示。

我从 Android.Net.Uri 获得了图片,但如何将其设置为 SharedPreferences 以及如何在 OnCreate() 中显示它?

将图像 uri 存储到共享首选项

SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
Editor editor = sharedpreferences.edit();
editor.putString("key_uri", "uri_value");
editor.commit();

存储后,当您在 onCreate() 中打开应用程序时检查此字符串

SharedPreferences prefs= getSharedPreferences(MyPREFERENCES, 0);
String image_uri= settings.getString("key_uri", "null");

然后把字符串image_uri转成Uri

Uri uri = Uri.parse(image_uri);

然后使用此 image_uri 放置并显示为图像。

我认为您不能直接将图像存储在共享首选项中。您可以将图像的绝对路径存储在存储或图像的 url 中,或者将图像位图转换为字节数组并将字节数组(字符串)存储在共享首选项中。

这里有两个选择。

  • 存储绝对路径或URI

        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("isSetImage", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("isSet", "true");
        editor.putString("absolutePath",filePath);
        editor.commit();
    

    你必须在'filepath'

  • 中给出绝对路径或URI
  • ByteArray转base64

Write 方法将位图编码为字符串 base64 和 return 来自位图的 base64 字符串

            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("isSetImage", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("isSet", "true");
        editor.putString("absolutePath",BitmapToBase64(mBitmap));
        editor.commit();

检查图片是否设置:

        SharedPreferences sharedPreferences1 = getActivity().getSharedPreferences("isSetImage", Context.MODE_PRIVATE);
    String isSet = sharedPreferences1.getString("isSet", "");
    String absPath = sharedPreferences1.getString("absolutePath", "");
    if(isSet.equalsIgnoreCase("true"))
    {
        if(absPath!=null){
            previewMedia(absPath);
        }
    }

注意:这是我的 android 工作室项目之一的代码。 Xamarin.Android

不会很难用

快乐编码\,/