5

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)

angryITguy
  • 9,332
  • 8
  • 54
  • 82
  • I need to send base64 text to browser. HTML5 at other end – angryITguy Feb 18 '12 at 13:26
  • \n isn't a carriage return character, it is a line feed. \r is the carriage return. https://stackoverflow.com/questions/3091524/what-are-carriage-return-linefeed-and-form-feed – Achille Dec 28 '17 at 16:48

1 Answers1

4

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.

beny23
  • 34,390
  • 5
  • 82
  • 85
  • When you mean by "chunking" it's putting a "\n" delimiter after each "chunk". So the commons Base64 would provide a "pure" base64 conversion ? – angryITguy Feb 18 '12 at 14:59
  • sun.misc classes don't exist in non-oracle JVMs while the commons Base64 works in all JVMs. Yes chunking puts a carriage return after every 76 characters. – beny23 Feb 18 '12 at 15:47
  • Ok. Just to confirm, the commons codec is compatible from 1.4? – angryITguy Feb 18 '12 at 22:21
  • As per http://commons.apache.org/codec/, Commons codec 1.4 and 1.5 are compatible with JDK 1.4 – beny23 Feb 20 '12 at 18:35
  • 1
    So does the commons ```Base64``` not insert ```\n``` ? – basZero Mar 19 '12 at 14:38
  • As per the [docs](http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html), `encodeBase64` doesn't and `encodeBase64Chunked` does insert line feeds. – beny23 Mar 19 '12 at 14:53
  • Strange how the default capability in sun.misc.Base64Encoder would chunk. Looking at it in "pure" data translation terms, it corrupts the data by default. I suppose the output was intended for VT220 terminals ? – angryITguy Apr 19 '12 at 04:44