12

I have a byte array representation of a Image. How to save it on disk as an image file.

I have already done this

OutputStream out = new FileOutputStream("a.jpg");
out.write(byteArray);
out.flush();
out.close();

But when I open the image by double-clicking it, it doesn't show any image.

4
  • do you mean to write it out as a PNG or JPG or just so that you can read it back in at some point? Commented Jan 26, 2010 at 11:06
  • do you have the kind of array you can pass to image.setRGB? Commented Jan 26, 2010 at 11:07
  • 1
    Where did you get the byte[] from? You need to know what format it has (JPEG, GIF, PNG, BMP...) Commented Jan 26, 2010 at 11:08
  • I think this is related to his other question : stackoverflow.com/questions/2138961/… Commented Jan 26, 2010 at 11:14

3 Answers 3

8

Other than failing to use a try/finally block (at least in the code you've shown) that should be fine. (You don't need to flush an output stream if you're closing it, by the way.)

As it's not working, that suggests byteArray doesn't actually contain a JPEG-encoded image. How have you created byteArray to start with? If it's a "raw" representation, you'll probably want to encode it, e.g. using the javax.imageio package.

Sign up to request clarification or add additional context in comments.

1 Comment

Could you also please look at stackoverflow.com/questions/2132657/… ................. Actually all suggested me to use MVC architecture of swing.... but I don't want that answer.... I already know it... I want a suggestion or a sample example of swing that has its gui code divided into several files... so that i can figure out my own problem... i searched on google a lot but couldn't get any such example...
8

You could use the FileOutputStream class:

FileOutputStream fos = new FileOutputStream("image.jpg");
try {
    fos.write(someByteArray);
}
finally {
    fos.close();
}

Comments

3

You can use ImageIO API.

The details can be a bit hairy, but first you'll probably want to create a BufferedImage using TYPE_BYTE_INDEXED type and some suitable IndexColorModel instance. Then put your byte array there. Hint: you can get the internal representation of BufferedImage with:

myDataBuffer = myBufferedImage.getRaster().getDataBuffer();

Which will likely return a data buffer of type DataBufferByte (check!), from which you get a byte array with

myByteArray = ((DataBufferByte) myDataBuffer).getData();

Then you can use System.arraycopy to copy your byte array onto that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.