aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes Convert between AWT Image and byte array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Convert between AWT Image and byte array" Watch "Convert between AWT Image and byte array" New topic
Author

Convert between AWT Image and byte array

Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1282

Hi folks,

I have an application which persists all data structures to an XML file. Some of the data objects have AWT Images as properties which should be saved to the XML file, too. I use JAXB for the marshalling and unmarshalling process. The binary data are marshalled to base64 encoded text in the XML file and the base64 data are unmarshalled to byte arrays in Java.

For this I need to convert between Images and byte arrays in both directions. I know there are many links on the internet and there are also discussion on JavaRanch but actually I couldn't find any good, working solution. What do you think would be the best idea to convert between Image and byte[]? Would you store the whole Image as jpg or png to XML or would it be a good plan to store only the raw image data? Perhaps some hints how to do this right?

Any help is welcome!

Marco
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

javax.imageio.ImageIO has a method called write which takes a RenderedImage, format name and OutputStream. That could be a ByteArrayOutputStream.

Now if your Image isn't an instance of RenderedImage then you can create a BufferedImage, paint the original image on that and use the BufferedImage (since BufferedImage implements RenderedImage):


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1282

Thanks a lot, Rob!

Your solution works perfectly. I just didn't know how to get a BufferedImage from my Image object.

Marco
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

The first check would be of course whether or not your Image may already be a RenderedImage. If so, why create the BufferedImage?
Marco Ehrentreich
best scout
Bartender

Joined: Mar 07, 2007
Posts: 1282

Good point! I'll include this check in my code!

Marco
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Convert between AWT Image and byte array