用JAVA从对象JSON中提取图像


Extract an image from an object JSON in JAVA

我正在尝试发送一个从数据库中获取的图像,我想使用用JSON编写的PHP WebApi将该图像发送到Java程序;以下几行是PHP程序的摘录:

$img = file_get_contents($stringPath);
$array = ["immagine" => base64_encode($img)];
echo json_encode($array);

在以下JAVA程序中,我使用restlet框架:

ClientResource resource = new ClientResource("link to the webApi");``
String retur = resource.get().getText();
JSONObject obj = new JSONObject(retur);

我如何从JSON对象中提取我从PHP程序发送的图像

如果我理解你的问题是正确的,你只需要像在php代码中那样做相反的步骤。

byte[] content = Base64.decodeBase64(obj.getString("immagine"));
ByteArrayInputStream bais = new ByteArrayInputStream(content);
BufferedImage image = ImageIO.read(bais);