如何存储位图对象在android的共享preferences [英] how to store bitmap object in sharedpreferences in android

查看:147
本文介绍了如何存储位图对象在android的共享preferences的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要存储在共享preferences和恢复方法的位图对象只检索该对象,并将其设置在background.Please告诉我如何存储和检索它的形式共享preferences.The问题是,共享preferences我们可以把值(如String),整型,bolean,长等,但不bitmao object.Please帮我理清这problem.Below是我的code:

  @覆盖
保护无效onResume(){
    super.onResume();rl_changeBackground.setBackgroundDrawable(新BitmapDrawable(getResources(),HomeSafeStaticVariables.bitmap));    }
    }


解决方案

您可以只添加布尔值,浮动,智力,长字符串值在共享preference。但有一件事你可以做的是位图转换为Base64字符串。而从共享prefrence检索之后将其转换为位图。

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

  ByteArrayOutputStream BAOS =新ByteArrayOutputStream();
bm.com preSS(Bitmap.Com pressFormat.PNG,100,BAOS); // BM是位图对象
字节[] B = baos.toByteArray();

从字节数组使用下面的方法连接code的base64

 字符串连接codeD = Base64.en codeToString(B,Base64.DEFAULT);

,并将其保存到共享prefrence。

现在假设你的图像数据是在一个名为EN codeD字符串,下面应该做给你Base64编码字符串的位图:

 字节[] = imageAsBytes Base64.de code(EN coded.getBytes());
ImageView的图像=(ImageView的)this.findViewById(R.id.ImageView);
image.setImageBitmap(BitmapFactory.de codeByteArray的(imageAsBytes,0,imageAsBytes.length));

这可能会帮助你。试着请让我知道!

I want to store the bitmap object in shared preferences and on resume method just retrieve that object and set it in background.Please tell me how to store and retrieve it form shared preferences.The problem is that in shared preferences we can put the values like String,int,bolean,long etc but not the bitmao object.Please help me to sort out this problem.Below is my code:

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

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

    }
    }

解决方案

You can add only Boolean, Float, Int, Long, String values in SharedPreference. But one thing you can do is converting Bitmap to Base64 String. And after retrieving it from SharedPrefrence convert it to Bitmap.

Use following method to convert bitmap to byte array:

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

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(b, Base64.DEFAULT); 

And Save it to SharedPrefrence.

Now assuming that your image data is in a String called encoded , the following should do give you BitMap from Base64 string:

byte[] imageAsBytes = Base64.decode(encoded.getBytes());
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length));

This may help you. Try and please let me know !

这篇关于如何存储位图对象在android的共享preferences的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆