Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a BufferedImage from and OutputStream

Tags:

java

I have a function, int readFully(FileHandle handle, OutputStream out), which reads in an entire file from an SSH server and stores it in a local stream. I can write the file locally by using a FileOutputStream for the second parameter and then read that file into a BufferedImage using something like this:

bufferedImage = ImageIO.read(new File("/path/to/file"));

But how can I create the bufferedImage directly without first writing it to a file? I looked at this question, but still can't figure it out for my case.

like image 284
gogators Avatar asked Jul 03 '13 15:07

gogators


People also ask

How to convert byte[] to BufferedImage?

This article shows how to convert a byte[] to a BufferedImage in Java. InputStream is = new ByteArrayInputStream(bytes); BufferedImage bi = ImageIO. read(is); The idea is puts the byte[] into an ByteArrayInputStream object, and we can use ImageIO.

How do I change an image to BufferedImage?

BufferedImage buffer = ImageIO. read(new File(file)); to Image i.e in the format something like : Image image = ImageIO.

How do I get OutputStream?

Methods of OutputStream Here are some of the methods: write() - writes the specified byte to the output stream. write(byte[] array) - writes the bytes from the specified array to the output stream. flush() - forces to write all data present in output stream to the destination.

What is BufferedImage in Java?

A BufferedImage is comprised of a ColorModel and a Raster of image data. The number and types of bands in the SampleModel of the Raster must match the number and types required by the ColorModel to represent its color and alpha components. All BufferedImage objects have an upper left corner coordinate of (0, 0).


1 Answers

Just write to a ByteArrayOutputStream instead - you can then create a ByteArrayInputStream to read from the same byte array, and then pass that to ImageIO.read(InputStream).

ByteArrayOutputStream output = new ByteArrayOutputStream();
readFully(handle, output);
byte[] data = output.toByteArray();
ByteArrayInputStream input = new ByteArrayInputStream(data);
BufferedImage image = ImageIO.read(input);

That's assuming you can't actually create an InputStream directly from the FileHandle, which would be even simpler.

like image 169
Jon Skeet Avatar answered Sep 21 '22 08:09

Jon Skeet