Question
How can I retrieve an InputStream from a BufferedImage object in Java?
BufferedImage bigImage = GraphicsUtilities.createThumbnail(ImageIO.read(file), 300);
ImageInputStream bigInputStream = ImageIO.createImageInputStream(bigImage);
Answer
Retrieving an InputStream from a BufferedImage can be accomplished using ByteArrayOutputStream. Since BufferedImage does not directly support InputStream creation, we will convert it to a byte array and then to an InputStream.
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class ImageStreamExample {
public static ByteArrayInputStream getInputStreamFromBufferedImage(BufferedImage image) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(baos);
ImageIO.write(image, "png", ios);
ios.flush();
return new ByteArrayInputStream(baos.toByteArray());
}
}
Causes
- `ImageIO.createImageInputStream()` does not accept a `BufferedImage` as a parameter; it only works with `File`, `ImageReader`, or other image sources.
- BufferedImage needs to be written to an `OutputStream` before transforming it into an `InputStream`.
Solutions
- Use a `ByteArrayOutputStream` to write the `BufferedImage` to a byte array.
- Convert the byte array to a `ByteArrayInputStream` to obtain an InputStream.
Common Mistakes
Mistake: Using ImageIO.createImageInputStream() with BufferedImage
Solution: Use ByteArrayOutputStream to first write the BufferedImage and then convert it to InputStream.
Mistake: Not flushing the ImageOutputStream
Solution: Always flush the output stream after writing the image to ensure all data is flushed to the ByteArrayOutputStream.
Helpers
- BufferedImage InputStream
- Java BufferedImage to InputStream
- ImageIO InputStream example
- Java InputStream from image
- BufferedImage InputStream conversion