Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Carriage return issue decoding Base64 from Java and sending to browser

I have a servlet that has resized and encoded an image into base64. I encode it like this

BufferedImage newBuf = .. a bufferedImage...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, sImgFormat, baos);
baos.flush();
imageInBytes = baos.toByteArray();

I then encode this into base64 to send to the browser like this

sun.misc.BASE64Encoder encoder = new BASE64Encoder();
String sEncImage = "data:image/jpg;base64," + encoder.encodeBuffer(imageInBytes);

The browser will receive the encoding and it works except for the carriage returns, ("\n") embedded consistently within the string which corrupts the image. When I remove the carriage returns the image is fine. Is there a way to generate the encoding without the carriage returns. Or must I filter it out myself before sending it back ?

(I am using J2SE 1.4.2 and need to continue to do so)

like image 683
angryITguy Avatar asked Oct 09 '22 15:10

angryITguy


1 Answers

I suspect that the sun.misc.Base64encoder is chunking the output. I wouldn't use sun.misc classes as it restricts your code to Oracle JVMs (for example, it would work in IBM Websphere). I'd use the commons Base64 encoder or Base64OutputStream.

like image 182
beny23 Avatar answered Oct 12 '22 10:10

beny23