2015-06-13 33 views
4

我有一個包含幾個字符串成員和一個位圖成員的對象。使用位圖轉換JSON對象

該對象被保存在一個包含String鍵和Object的映射中作爲值。

我使用以下代碼來對地圖轉換:

String json = new Gson().toJson(aMap); 

,然後提取我使用JSON地圖(通過上述JSON字符串):

Map<String, Object> aMap; 
    Gson gson = new Gson(); 
    aMap = gson.fromJson(jsonString, new TypeToken<Map<String, Object>>() {}.getType()); 

這種部分作品但存儲在對象中的位圖似乎損壞?即當我嘗試將位圖應用於圖像視圖時,我得到一個異常。

我在想我可能需要單獨將位圖轉換爲JSON字符串,但希望有一個更簡單的解決方案,任何想法?

謝謝。

回答

8

這其實很簡單:

private String getStringFromBitmap(Bitmap bitmapPicture) { 
/* 
* This functions converts Bitmap picture to a string which can be 
* JSONified. 
* */ 
final int COMPRESSION_QUALITY = 100; 
String encodedImage; 
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream(); 
bitmapPicture.compress(Bitmap.CompressFormat.PNG, COMPRESSION_QUALITY, 
byteArrayBitmapStream); 
byte[] b = byteArrayBitmapStream.toByteArray(); 
encodedImage = Base64.encodeToString(b, Base64.DEFAULT); 
return encodedImage; 
} 

,反之亦然:

private Bitmap getBitmapFromString(String jsonString) { 
/* 
* This Function converts the String back to Bitmap 
* */ 
byte[] decodedString = Base64.decode(stringPicture, Base64.DEFAULT); 
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
return decodedByte; 
} 

這不是我的,我把它從HERE

+0

完美的工作,我改變了對象的位圖作爲字符串,然後轉換回圖像應用到imageView使用上述代碼。 – ScottishUser