首页 > 解决方案 > 如何存储登录的用户图像以在抽屉中使用?我已成功存储用户名电子邮件和其他文本信息

问题描述

我已成功将登录的用户信息(如用户名、用户电子邮件和其他重要信息)存储在共享首选项中。但我正在寻找存储用户图像的最佳方式。

标签: android

解决方案


您仍然可以使用 sharedpreference,因为您也将其他信息存储在 sharedpreference 中。您所要做的就是将您的图像转换为它的Base64字符串表示形式:

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();

然后,在检索时,将其转换回位图:

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);
}

但是,我必须告诉你,Base64支持只是最近才包含在 API8 中。要针对较低的 API 版本,您需要先添加它。幸运的是,这个人已经有了所需的教程。

github上有一个快速而肮脏的例子。

原始线程在这里

希望能帮助到你!


推荐阅读