从 Java 解码 Base64 并发送到浏览器的回车问题
我有一个 Servlet,它已调整图像大小并将图像编码为 Base64。我像这样对其进行编码,
BufferedImage newBuf = .. a bufferedImage...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, sImgFormat, baos);
baos.flush();
imageInBytes = baos.toByteArray();
然后将其编码为 base64 以发送到浏览器,如下所示
sun.misc.BASE64Encoder encoder = new BASE64Encoder();
String sEncImage = "data:image/jpg;base64," + encoder.encodeBuffer(imageInBytes);
浏览器将接收编码,并且除了回车符(“\n”)一致嵌入到破坏图像的字符串中之外,它可以正常工作。当我删除回车符时,图像很好。有没有一种方法可以生成不带回车的编码。或者我必须在寄回之前自己过滤掉它?
(我正在使用J2SE 1.4.2并且需要继续这样做)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑 sun.misc.Base64encoder 正在对输出进行分块。
我不会使用 sun.misc 类,因为它将您的代码限制为 Oracle JVM(例如,它可以在 IBM Websphere 中工作)。我会使用公共 Base64 编码器或 Base64OutputStream。
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.