Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Convert between AWT Image and byte array

 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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):
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good point! I'll include this check in my code!

Marco
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic