Java - Image encoding in XML

Posted by Hoopla on Stack Overflow See other posts from Stack Overflow or by Hoopla
Published on 2009-08-21T15:58:48Z Indexed on 2010/05/31 17:53 UTC
Read the original article Hit count: 173

Filed under:
|
|
|

Hi everyone,

I thought I would find a solution to this problem relatively easily, but here I am calling upon the help from ye gods to pull me out of this conundrum.

So, I've got an image and I want to store it in an XML document using Java. I have previously achieved this in VisualBasic by saving the image to a stream, converting the stream to an array, and then VB's xml class was able to encode the array as a base64 string. But, after a couple of hours of scouring the net for an equivalent solution in Java, I've come back empty handed. The only success I have had has been by:

import it.sauronsoftware.base64.*;
import java.awt.image.BufferedImage;
import org.w3c.dom.*;

...

      BufferedImage img;
      Element node;

      ...

      java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();

      ImageIO.write(img, "png", os);

      byte[] array = Base64.encode(os.toByteArray());

      String ss = arrayToString(array, ",");

      node.setTextContent(ss);

      ...

  private static String arrayToString(byte[] a, String separator) {
    StringBuffer result = new StringBuffer();
    if (a.length > 0) {
        result.append(a[0]);
        for (int i=1; i<a.length; i++) {
            result.append(separator);
            result.append(a[i]);
        }
    }
    return result.toString();
  }

Which is okay I guess, but reversing the process to get it back to an image when I load the XML file has proved impossible. If anyone has a better way to encode/decode an image in an XML file, please step forward, even if it's just a link to another thread that would be fine.

Cheers in advance,

Hoopla.

© Stack Overflow or respective owner

Related posts about java

Related posts about Xml