我成功地在共享首选项中存储了登录的用户信息,如用户名、用户电子邮件和其他重要信息。但我正在寻找存储用户图像的最好方法。
发布于 2018-08-12 00:17:21
你仍然可以使用共享首选项,因为你也可以在共享首选项中存储其他信息。您所要做的就是将您的图像转换为它的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);
}
但是,我必须告诉您,API8最近才包含了对Base64的支持。要针对较低的API版本,您需要先添加它。幸运的是,this guy已经有了所需的教程。
github上有一个quick and dirty example。
原始线程here。
希望它能帮上忙!
https://stackoverflow.com/questions/51801489
复制相似问题