Android SharedPreferences保存位图 [英] Android SharedPreferences Save bitmap

查看:186
本文介绍了Android SharedPreferences保存位图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序上有一个活动,该活动必须保存一些数据,并且该数据必须从其他活动中获取,所以我正在使用SharedPreferences来执行此操作,问题是,当我尝试保存位图时ImageView的内容:

I have an Activity on my app that has to save some data, and that data has to be accesed from other Activity, so i´m using SharedPreferences to do this, the problem is that, when i try to save the bitmap of an ImageView with:

ImageButton imgView = (ImageButton) findViewById(R.id.UserImageButton);
Bitmap bitmap = ((BitmapDrawable)imgView.getDrawable()).getBitmap();
editor.putInt("bitmap", bitmap);

或直接与:

ImageButton imgView = (ImageButton) findViewById(R.id.UserImageButton);;
editor.putInt("bitmap", ((BitmapDrawable)imgView.getDrawable()).getBitmap());

但是它不起作用. 我该如何保存?非常感谢

But it doesn´t work. How can I save it?? Thanks a lot

推荐答案

您只能在SharedPreference中添加布尔值,浮点数,整数,长整数,字符串值.但是您可以做的一件事是将Bitmap转换为Base64 String.然后从SharedPrefrence检索到它,然后将其转换为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();

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

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(b, Base64.DEFAULT); 
And Save it to SharedPrefrence.

现在,假设您的图像数据在一个名为"encoded"的字符串中,那么下面的代码应该可以为您提供来自Base64字符串的BitMap:

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));

:)

这篇关于Android SharedPreferences保存位图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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