如何在android中的sharedpreferences中存储位图对象

Dee*_*rma 3 android bitmap

我想将位图对象存储在共享首选项和resume方法中,只需检索该对象并在后台设置它.请告诉我如何以共享首选项存储和检索它.问题是在共享首选项中我们可以将值放在String,int,bolean,long等但不是bitmao对象.请帮我解决这个问题.下面是我的代码:

    @Override
protected void onResume() {
    super.onResume();

rl_changeBackground.setBackgroundDrawable(new BitmapDrawable(getResources(),HomeSafeStaticVariables.bitmap));

    }
    }
Run Code Online (Sandbox Code Playgroud)

Akh*_*ani 18

您只能在SharedPreference中添加Boolean,Float,Int,Long,String值.但您可以做的一件事是将Bitmap转换为Base64 String.从SharedPrefrence检索后将其转换为Bitmap.

使用以下方法将位图转换为字节数组:

ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray();
Run Code Online (Sandbox Code Playgroud)

使用以下方法从字节数组中编码base64

String encoded = Base64.encodeToString(b, Base64.DEFAULT); 
Run Code Online (Sandbox Code Playgroud)

并将其保存到SharedPrefrence.

现在假设你的图像数据在一个名为encoded的字符串中,以下应该从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));
Run Code Online (Sandbox Code Playgroud)

这可能对你有所帮助.试试,请告诉我!


nul*_*ter 3

您可以将位图存储为base64字符串SharedPreferences。但是将位图图像存储在SharedPreferences. 您应该将图像存储在SD卡中,并将路径保存在SharedPreferences.

检查这个问题