smuggledPancakes
smuggledPancakes

Reputation: 10323

How do I take bytes and make a image file out of it in Java?

A person on my team is computing a task that results in an array of RGB bytes. The program runs headless environment on a server, so does that mean I can't import any awt classes? I want to use an OutputStream to send the bytes to browser in a HTTP GET. I have it all working with a PNG file that is saved on the server's HDD, but now I want to use a byte[] instead of a File.

My code looks like this now for reading a file. I am having trouble making it work for a byte[]. I tried just feeding the outputstream some random bytes but I never get an image in the browser. I know it will not look like the file, but I expected something random to show up, but nothing did.

File file = new File("images/test.png");
FileInputStream in = new FileInputStream(file);
OutputStream out = new OutputStream();
byte[] buf = new byte[1024];
int count = 0;
while((count = in.read(buf)) >=  0)
{
   out.write(buf, 0, count);
}
out.close;
in.close;

Upvotes: 0

Views: 440

Answers (1)

Harald K
Harald K

Reputation: 27084

You can safely use classes like BufferedImage, Raster, DataBuffer and ImageIO in a headless environment. Classes and methods that can't be used in headless mode, are typically marked with:

@throws HeadlessException if GraphicsEnvironment.isHeadless() returns true.

This typically includes Swing and AWT components, like windows, buttons, etc. See for example usages of HeadlessException for a list of methods and classes that has this limitation.

Now that you know this, all you have to do, is get the "raw" RGB bytes into a BufferedImage using the setRGB(...) method, or accessing the DataBuffer's backing array directly. Multiple Q&As about this are available on SO already (google for "creating a BufferedImage from bytes").

@rayryeng is of course correct in that you need to know the pixel layout and width/height of the image, to be able to reconstruct it. It would probably be easier for you, if the other developer could just send you the image in a known format, like PNG or similar.

When you have a BufferedImage ready, write the image to the servlet output stream, using ImageIO like this:

OutputStream out = ...; // the servlet or socket output stream
BufferedImage image = ...; // the image you just created

if (!ImageIO.write(image, "PNG", out)) {
    log.warn("Could not write image...");
}

Upvotes: 2

Related Questions