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

Phill Alexakis :

i'm creating a BufferedImage and i'm trying to include it to a MimeBodyPart as follows:

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

Is there any way to attach a BufferedImage without creating a File?

Please assume that

  • generateQR() exists
  • There is an HTML MimeBodyPart
Arnaud :

As suggested, you may get the bytes from your image, and use the according datasource.

This is based on the questions :

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

and

javamail problem: how to attach file without creating file

You may end up with something like :

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

Edit :

As the databuffer may not always be a DataBufferByte, you may put the image data in a byte array that way :

Replace

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

with the following operations :

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

(example inspired from How I can convert BufferedImage to a byte array without using files)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=132463&siteId=1