1

How can I convert an image like this one into a Base64 string? I upload the image to the server with React, scale it, save it in the database, read it out again and get this format. Now I have to convert this format into a Base64 format.

My Java Code to scale the image:

        Part bild = request.getPart("bild");
        InputStream in = null;
        long fileSize = bild.getSize();
        byte[] bytesBild = null;
        if (fileSize > 0) {

            in = bild.getInputStream();

            BufferedImage imBuff = ImageIO.read(bild.getInputStream());
            BufferedImage resize = resizeImage(imBuff, 200, 200);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(resize, "jpeg", os); // Passing: ​(RenderedImage im, String formatName, OutputStream
                                                // output)
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            bytesBild = IOUtils.toByteArray(is);

        }

This is the result from my Database:

enter image description here

Jens
  • 67,715
  • 15
  • 98
  • 113
schorle88
  • 103
  • 6

1 Answers1

3

You could use the native java.util.Base64 class.

Save to database

//...
bytesBild = IOUtils.toByteArray(is);
String imgEncodedString = Base64.getEncoder().encodeToString(bytesBild);

//imgEncodedString --> ddbb

Read from database

 byte[] imgDecodedBytes = Base64.getDecoder().decode(imgEncodedString); 
 ByteArrayInputStream bis = new ByteArrayInputStream(imgDecodedBytes);
 //...
aran
  • 10,978
  • 5
  • 39
  • 69