How to get an InputStream from a BufferedImage?

JavaImage Processingjavax.imageio

Java Problem Overview


How can I get an InputStream from a BufferedImage object? I tried this but ImageIO.createImageInputStream() always returns NULL

BufferedImage bigImage = GraphicsUtilities.createThumbnail(ImageIO.read(file), 300);
ImageInputStream bigInputStream = ImageIO.createImageInputStream(bigImage);

The image thumbnail is being correctly generated since I can paint bigImage to a JPanel with success.

Java Solutions


Solution 1 - Java

From http://usna86-techbits.blogspot.com/2010/01/inputstream-from-url-bufferedimage.html

It works very fine!

> Here is how you can make an > InputStream for a BufferedImage: > > URL url = new URL("http://www.google.com/intl/en_ALL/images/logo.gif";); > BufferedImage image = ImageIO.read(url); > ByteArrayOutputStream os = new ByteArrayOutputStream(); > ImageIO.write(image, "gif", os); > InputStream is = new ByteArrayInputStream(os.toByteArray());

Solution 2 - Java

If you are trying to save the image to a file try:

ImageIO.write(thumb, "jpeg", new File(....));

If you just want at the bytes try doing the write call but pass it a ByteArrayOutputStream which you can then get the byte array out of and do with it what you want.

Solution 3 - Java

By overriding the method toByteArray(), returning the buf itself (not copying), you can avoid memory related problems. This will share the same array, not creating another of the correct size. The important thing is to use the size() method in order to control the number of valid bytes into the array.

final ByteArrayOutputStream output = new ByteArrayOutputStream() {
	@Override
	public synchronized byte[] toByteArray() {
		return this.buf;
	}
};
ImageIO.write(image, "png", output);
return new ByteArrayInputStream(output.toByteArray(), 0, output.size());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlbrandaoView Question on Stackoverflow
Solution 1 - JavaFelipeView Answer on Stackoverflow
Solution 2 - JavaTofuBeerView Answer on Stackoverflow
Solution 3 - JavaIgorView Answer on Stackoverflow