简体   繁体   中英

Read byte array into base64 encoded image

I'm trying to read an image into a ByteArrayOutputStream and then encode the array into Base64 for sending as part of a json to my API. I'm wanting to avoid saving it anywhere and just read it, encode, and send. Unfortunately, when I use the ByteArrayOutputStream.toByteArray() as a parameter in Base64.getEncoder.encodeToString() method it returns a String that contains extra break characters '\\' in the String as compared to a successful test reading from a File into Base64.

Is it possible to read directly from the byte array into base 64? Or will I have to translate into an image then to base 64?

Any help is appreciated.

Getting Image from base64:

byte[] b = DatatypeConverter.parseBase64Binary(base64Img);
ByteArrayInputStream s = new ByteArrayInputStream(b);
return new Image(s);

Maybe it can help you to do the reverse.

Apparently, passing the outputstream directly into the encoder was the issue. I added a local variable to reference the byte[] and then pass it into the encoder and it now works.

byte[] array = outputStream.toByteArray();
String base64String = Base64.getEncoder().encodeToString(array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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