Forums Register Login

Convert between AWT Image and byte array

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
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):
+Pie Number of slices to send: Send
Thanks a lot, Rob!

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

Marco
+Pie Number of slices to send: Send
The first check would be of course whether or not your Image may already be a RenderedImage. If so, why create the BufferedImage?
+Pie Number of slices to send: Send
Good point! I'll include this check in my code!

Marco
Self destruct mode activated. Instructions for deactivation encoded in this tiny ad.
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 15382 times.
Similar Threads
How do i call a java method from xsl?
Convert byte[] to String
Saving a byteArray in XML and retrieving it in Java
storing attachment files in xml / reading from xml
How to preserve xmp metadata when resizing jpg images
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 07:01:17.