从 Java 解码 Base64 并发送到浏览器的回车问题

发布于 2025-01-07 00:35:59 字数 620 浏览 7 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

書生途 2025-01-14 00:35:59

我怀疑 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文