如何在不创建文件对象的情况下将 BufferedImage 附加到 MimeBodyPart

How to attach a BufferedImage to a MimeBodyPart without creating a File object

我正在创建一个 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

请假设

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

这是基于以下问题:

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();

(示例灵感来自