将图像转换为base64并以json格式发送

时间:2014-04-09 18:05:46

标签: java android

我正在尝试将图像转换为base64,然后将它们作为JSON字符串的一部分发送,除非我有2张图像,否则一切正常。发生的事情是我只在JSON和服务器端获得第二个图像两次,但我没有看到为什么会发生这种情况..

这是我的代码:

JSONObject jsonPhotos = new JSONObject();
if (photos != null) {
    try {
        JSONArray jsonObj = new JSONArray(photos);
        for (int i = 0; i < jsonObj.length(); i++) {
            JSONObject c = jsonObj.getJSONObject(i);
            String imageUrl = c.getString("url");

            System.out.println( "each urls: " + imageUrl );

            String cap = c.getString("caption");
            //get to base64
            Bitmap bm = BitmapFactory.decodeFile(imageUrl);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            bm.compress(Bitmap.CompressFormat.JPEG, 10, baos); //bm is the bitmap object   
            byte[] b = baos.toByteArray(); 
            String encodedString = Base64.encodeToString(b, Base64.DEFAULT);
            jsonPhotos.put( "imageData", encodedString);
            jsonPhotos.put( "caption", cap);

            claim.accumulate( "photos", jsonPhotos);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
} else {
}

在我的日志中,每个网址都不同。但当它被放入json时,base64编码的字符串是相同的。

1 个答案:

答案 0 :(得分:0)

在循环的每次迭代中创建一个新的jsonPhotos项。 发生的事情是你在循环开始之前创建一个JSON对象,然后你不断更新它&#34; itemData&#34;通过循环的每次迭代。

我怀疑&#34; claim.accumulate&#34;正在持有传入其中的JSONObject的引用,而不是进行深层复制。这应该解决它。

if (photos != null) {
    try {
        JSONArray jsonObj = new JSONArray(photos);
        for (int i = 0; i < jsonObj.length(); i++) {

            ...

        JSONObject jsonPhotos = new JSONObject();  // add this line here

        jsonPhotos.put( "imageData", encodedString);
        jsonPhotos.put( "caption", cap);

        claim.accumulate( "photos", jsonPhotos);

    }
相关问题