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上有一个快速而肮脏的例子。
原始线程在这里。
希望能帮助到你!
推荐阅读
- python - 在 React 网站中实现 Python 程序
- python - 创建一个填充自定义格式文本的文本文件
- mysql - 为音乐数据库编写 SQL 查询
- wordpress - 如何从运输中删除条款+订单按钮并将其添加到运输表格下?
- wkhtmltopdf - QPaintDevice:无法销毁正在绘制的绘制设备纯虚拟方法称为终止调用而没有活动异常
- c# - 在 linq 中创建一个树结构,其中包含单个列表源,其父 - 子作为对象的字符串
- javascript - javascript中是否有用于切换样式标签的功能?
- javascript - 使用 Vanilla JS 问题滚动到顶部按钮
- python - 通过 Python 将数据合并到 Excel 中的 1 个工作表中
- java - 如何从二维数组中获取奇数行或偶数行?