使用位图转换JSON对象

时间:2015-06-13 12:13:04

标签: android json bitmap

我有一个包含几个字符串成员和一个位图成员的对象。

对象保存在带有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的字符串,但希望这是一个更简单的解决方案,任何想法?

感谢。

1 个答案:

答案 0 :(得分:10)

这实际上很简单:

 /*
 * This functions converts Bitmap picture to a string which can be
 * JSONified.
 * */
private String getStringFromBitmap(Bitmap bitmapPicture) {
   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;
 }

反之亦然:

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

这不是我的,我是从HERE取得的。