views:

340

answers:

4

Hey,

how can I use Castor XML to marshal a java.awt.Image object to XML, or make the XML reference the image in some way.

Cheers,
Pete

A: 

I don't know if you can store the image directly. You could try to get the raster and store each pixel.

Geo
How would it be possible to store with width and height of the image?
Malachi
The width and height are ints too, and can be obtained with the getHeight() and getWidth() methods.
Geo
+1  A: 

I guess you could write your own field handler. Me, I'd write the image itself to a location and reference the image from within the xml.

Jan Jungnickel
A: 

This depends entirely on what will consume the XML. As jjungnickel, said, the easiest way to do this is to write the image to a file and then reference this file within XML. You can do this by:

  • Put the filename (relative or absolute) in the XML
  • Put an XML entity reference in the XML, which may or may not work depending on how the image is encoded

Images -- binary content -- can go into XML, but it requires more special handling. It's a lot easier to put the filename into XML and then to open that file separately, but this depends on the needs of the consumer of the XML.

Now, if you want to use Castor to do this, it's a lot easier to serialize the filename rather than the image itself. If you want to put the image itself in the XML, you'll need to write a custom field handler. When I've used Castor for XML that involved images, I always put the filename in the XML, not the image itself, and then the XML consumer read the filename and used that to serialize the image.

Eddie
A: 

You could certainly base64 encode a gif/jpg/whatever an wrap it in an or whatever sort of tag. As Jan suggested, you can use a custom FieldHandler to do this (which I haven't done in Castor for at least five years).

The real question is this: What is your goal? Are you trying to design an inter-op scheme that can pass image data along with "normal" information? Are you trying to persist your data as XML in your own systems? If you are trying to do inter-op, I'd go the Base64 route for simplicity. Almost any language with an XML parser will have a Base64 package as well, so it wouldn't place an undue burden on the other party.

If you are persisting XML documents within systems that you control, I'd consider the other posters' suggestion to provide a key in the XML to an image file stored somewhere, especially if the images are large or numerous.

ShabbyDoo