2015-12-20 98 views
0

我有一個活動在我的應用程序,必須保存一些數據,並且該數據必須從其他活動,所以我使用SharedPreferences來做到這一點,問題是,當我嘗試要保存的ImageView的位圖:Android SharedPreferences保存位圖

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

但doesn't工作。 如何保存?非常感謝

+1

您需要將其保存在字符串base64中,而不是int –

+2

可能的重複[如何在Android中使用sharedpreference存儲圖像?](http://stackoverflow.com/questions/8586242/how-can-i-store -images-using-sharedpreference-in-android) –

+1

請將圖像保存爲普通文件。 – CommonsWare

回答

0

您只能在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); 
And Save it to SharedPrefrence. 

現在假設你的圖像數據是在一個叫做編碼的字符串,以下應該會給你從Base64字符串給你BitMap:

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

:)

+0

不,不要這樣做,將位圖轉換爲字符串完全沒有必要將其存儲在SharedPreferences中,然後將其轉換爲顯示它。 – Karakuri

-1

沒有理由在SharedPreferences中存儲整個位圖。將其保存爲普通文件。如果您必須在SharedPreferences中存儲任何內容,則只需存儲文件路徑。