How to convert BufferedImage to InputStream?

user405398 picture user405398 · Nov 23, 2010 · Viewed 33k times · Source

I am uploading images using servlet. To perform resize operations i am converting InputStream to BufferedImage. Now i want to save it in mongoDB. Since, i am new to mongoDB as far as i know, GridFS takes InputStream.

So, is there any way to convert BufferedImage to InputStream?

Answer

Sorter picture Sorter · Feb 5, 2014

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.