我想将位图对象存储在共享首选项中,并在恢复方法中检索该对象并将其设置在后台。请告诉我如何从共享首选项中存储和检索它。问题是在共享首选项中我们可以放置String、int、bolean、long 等值,但不是 bitmao 对象。请帮我解决这个问题。下面是我的代码:
@Override
protected void onResume() {
super.onResume();
rl_changeBackground.setBackgroundDrawable(new BitmapDrawable(getResources(),HomeSafeStaticVariables.bitmap));
}
}
您只能在 SharedPreference 中添加 Boolean、Float、Int、Long、String 值。但是您可以做的一件事是将位图转换为 Base64 字符串。在从 SharedPrefrence 检索它之后将其转换为位图。
使用以下方法将位图转换为字节数组:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
使用下面的方法从字节数组编码base64
String encoded = Base64.encodeToString(b, Base64.DEFAULT);
并将其保存到 SharedPrefrence。
现在假设您的图像数据在一个名为 encoded 的 String 中,下面应该会为您提供来自 Base64 字符串的 BitMap:
byte[] imageAsBytes = Base64.decode(encoded.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));
这可能对您有所帮助。试试看,请告诉我!