繁体   English   中英

将图像转换为base64并作为json发送

[英]converting images to base64 and sending as json

我正在尝试将图像转换为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编码的字符串是相同的。

在循环的每次迭代中创建一个新的jsonPhotos项目。 发生的事情是,您在循环开始之前创建了一个JSON对象,然后在循环的每次迭代中不断更新其“ itemData”。

我怀疑“ claim.accumulate”会保留传递给它的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);

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM