【问题标题】:How to attach a BufferedImage to a MimeBodyPart without creating a File object如何在不创建 File 对象的情况下将 BufferedImage 附加到 MimeBodyPart
【发布时间】:2019-08-09 17:01:27
【问题描述】:

我正在创建一个 BufferedImage,我正在尝试将它包含到 MimeBodyPart 如下:

BufferedImage img=generateQR(otp);
messageBodyPart = new MimeBodyPart();
File test = new File("phill.png");
ImageIO.write(img, "png", test);
DataSource fds = new FileDataSource(test);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setFileName("./phill.png");
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);
test.delete();

有没有办法在不创建File 的情况下附加BufferedImage

请假设

  • generateQR() 存在
  • 有一个 HTML MimeBodyPart

【问题讨论】:

标签: java jakarta-mail


【解决方案1】:

按照建议,您可以从图像中获取字节,并使用相应的数据源。

这是基于问题:

Java- Convert bufferedimage to byte[] without writing to disk

javamail problem: how to attach file without creating file

你可能会得到类似的结果:

byte[] imageBytes = ((DataBufferByte) img.getData().getDataBuffer()).getData();

ByteArrayDataSource bds = new ByteArrayDataSource(imageBytes, "image/png"); 
messageBodyPart.setDataHandler(new DataHandler(bds)); 
messageBodyPart.setFileName("./phill.png");
messageBodyPart.setHeader("Content-ID", "<image>");
multipart.addBodyPart(messageBodyPart);

编辑:

由于数据缓冲区可能并不总是DataBufferByte,您可以这样将图像数据放入字节数组中:

替换

byte[] imageBytes = ((DataBufferByte) img.getData().getDataBuffer()).getData();

通过以下操作:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
baos.flush();
byte[] imageBytes= baos.toByteArray();
baos.close();

(示例来自How I can convert BufferedImage to a byte array without using files

【讨论】:

  • 我认为img.getData().getBuffer() 会返回DataBufferInt,并且由于演员阵容,我得到了java.awt.image.DataBufferInt cannot be cast to java.awt.image.DataBufferByte at SendEmailSMTP.sendEmail(SendEmailSMTP.java:46)
  • ImageIO.write() 正在创建一个本地 png 不是吗?
  • 这里不是本地文件,它写入你想要的输出流,在这种情况下它是一个内存中的“流”。
  • 对,很抱歉,我没有看到您正在写信给ByteArrayOutputStream
  • 第一个提议的解决方案只有在图像的数据缓冲区已经包含 PNG 编码数据时才有效。这是无法预料的,​​因为该图像以前可能从未是 PNG。 ImageIO.write() 是确保您获得某种格式的图像数据的唯一可靠方法。
猜你喜欢
  • 2017-11-26
  • 2020-01-24
  • 1970-01-01
  • 1970-01-01
  • 2020-08-04
  • 1970-01-01
  • 2019-07-01
  • 2021-09-16
  • 2013-03-01
相关资源
最近更新 更多