在JAVA中从JSON String获取图像

时间:2012-12-04 18:09:45

标签: java android

我从php发送JSON字符串给Java,它包含一些字符串类型数据和编码图像。在jJva中,inputStream被转换为BufferedReader和String。现在字符串看起来像{"name": "xxx", "image":agrewfefe...} 有没有办法解码表示图像到位图的字符串,或者我必须在其他流中发送图像?

2 个答案:

答案 0 :(得分:1)

是;你需要Base64 encode你的形象。

因为它不能保证您生成的字符是可打印的,或者它们不会破坏JSON格式。

有许多Base64编码/解码库。常用的一个包含在Apache commons (codec) library

以下是http://www.kodejava.org/examples/375.html

中的简单用法示例
import org.apache.commons.codec.binary.Base64;
import java.util.Arrays;

public class Base64Encode {
    public static void main(String[] args) {
        String hello = "Hello World";

        //
        // The encodeBase64 method take a byte[] as the paramater. The byte[] 
        // can be from a simple string like in this example or it can be from
        // an image file data.
        //
        byte[] encoded = Base64.encodeBase64(hello.getBytes());

        //
        // Print the encoded byte array
        //
        System.out.println(Arrays.toString(encoded));

        //
        // Print the encoded string
        //
        String encodedString = new String(encoded);
        System.out.println(hello + " = " + encodedString);
    }
}

在发送方面,您将使用该编码字符串为您的JSON“图像”字段。另一端你会解析JSON,然后将你的Base64字符串解码回图像。

编辑添加:重新阅读您的问题(我最初只注意了标签而错过了PHP部分) - 在PHP方面,您需要使用base64_encode < / p>

http://php.net/manual/en/function.base64-encode.php

答案 1 :(得分:1)

如上所述,Base64编码是可行的方法。但是不要手动执行此操作,只需使用Jackson JSON library,它会自动Base64对二进制数据进行编码/解码(任何声明为byte[]的内容)。像

这样的东西
public class Request {
  public String name;
  public byte[] image;
}

Request req = new ObjectMapper().readValue(new URL("http://my.service.com/getImage?id=123"),
  Request.class);