Is it possible to convert an image to a string in JSON format?

Asked

Viewed 2,212 times

1

I wonder if it is possible to convert an image to a string in JSON format. If so, could you explain to me how? (if possible with example codes). I need to do this to send these images to a web service that will be responsible for storing it in the database.

  • 2

    Theoretically you will have to convert the image into a byte array (byte[]) and then put inside your JSONObject. Take a look here

  • I’m taking a look, thank you for responding. I’ll try to do something here and then put the result.

  • @Pauloh.Hartmann, I was able to convert the image to an array of bytes. The problem now is that the library I’m using Gson does not directly convert an array of bytes to a JSON string. This JSONObject that you mentioned only exists on android right?

  • With the help of the library Base64 you can pass this your byte array to a String. Starts a new object Base64 and uses the function encodeAsString(seuArrayBytes). Thus: Base64 base = new Base64();
 String encoded = base.encodeAsString(byteArray); (I’m not sure about that, but it’s worth the test)

  • JsonObject is part of the library gsoncom.google.gson.

1 answer

5


Leaving the answer here for anyone who goes through the same doubt I did.

    /*Primeiro, importa-se a imagem e a converte para um array de bytes*/
    BufferedImage imagem = ImageIO.read(new File("sua_imagem.jpg"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ImageIO.write(imagem, "jpg", baos);
    arrayBytes = baos.toByteArray();

    /*Depois usamos a biblioteca Base64 para converter o array de bytes em uma string*/
    String encoded = Base64.getEncoder().encodeToString(arrayBytes);

    /*Por fim, utilizamos a biblioteca JSON Simple para criar uma string no formato JSON utilizando os dados do encoded que conseguimos ao converter o array de bytes com o Base64*/

    JSONObject jo = new JSONObject();
    jo.put("imagem", encoded);
    String jsonImagem = jo.toJSONString();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.