How to convert BufferedImage to InputStream?

You need to save the BufferedImage to a ByteArrayOutputStream using the ImageIO class, then create a ByteArrayInputStream from toByteArray().


First of all you must get your "bytes":

byte[] buffer = ((DataBufferByte)(bufferedImage).getRaster().getDataBuffer()).getData();

And then use ByteArrayInputStream(byte[] buf) constructor to create your InputStream;


BufferedImageByteArrayOutputStreambyte[]ByteArrayInputStream

Use the ImageIO.write method to make a BufferedImage (which is a RenderedImage) into a ByteArrayOutputStream. From there get a byte array (byte[]), feeding that into an InputStream of type ByteArrayInputStream.

ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(buffImage, "jpeg", os);                          // Passing: ​(RenderedImage im, String formatName, OutputStream output)
InputStream is = new ByteArrayInputStream(os.toByteArray());

Both the ByteArrayOutputStream and InputStream implement AutoCloseable. So you can conveniently have those closed automatically by using try-with-resources syntax.