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.
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.
BufferedImage buffer = ImageIO. read(new File(file)); to Image i.e in the format something like : Image image = ImageIO.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With