Saving binary data in XML

You can encode the binary data in base-64 format. The following example Image2XML creates an XML and stores an image, encoded in base-64 format, in one of the tags. XML2Image does the opposite: given the XML, it will convert the base-64 back to binary and save it in a file.

The XML structure it creates looks like this:

<xmlimage>
   <format></format>
   <width></width>
   <height></height>
   <data></data>
</xmlimage>

Image2XML.java:

import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
 
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
 
import javax.swing.*;
import java.awt.*;
import java.io.*;
   
public class Image2XML
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Image2XML <image>");
         System.exit(1);
      }
 
      // get format, width and height 
      String format = "";
      int findex = args[0].indexOf(".");
      if (findex > -1) {
         format = args[0].substring(findex+1);
      }
   
      ImageIcon imageIcon = new ImageIcon(args[0]);
      Image img = imageIcon.getImage();
 
      double width  = img.getWidth(null);
      double height = img.getHeight(null);       
 
      // get binary data and convert to base64 
      byte[] buffer = null;
      try {
         buffer = readBinaryFile(args[0]);
      }
      catch(Exception e) {
         e.printStackTrace();
         System.exit(1);
      }
 
      String data = new sun.misc.BASE64Encoder().encode(buffer);
  
      // create XML document
      Document doc;
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.newDocument();
  
         Element xmlimageEl = doc.createElement("xmlimage");
         Element formatEl   = doc.createElement("format");
         Element widthEl    = doc.createElement("width");
         Element heightEl   = doc.createElement("height");
         Element dataEl     = doc.createElement("data");
         xmlimageEl.appendChild(formatEl);
         xmlimageEl.appendChild(widthEl);
         xmlimageEl.appendChild(heightEl);
         xmlimageEl.appendChild(dataEl);
 
         formatEl.appendChild(doc.createTextNode(""+format));
         widthEl.appendChild(doc.createTextNode(""+width));
         heightEl.appendChild(doc.createTextNode(""+height));
         dataEl.appendChild(doc.createTextNode(data));
 
         doc.appendChild(xmlimageEl);
  
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer transformer = tf.newTransformer();
         PrintWriter pw = new PrintWriter(new FileWriter(args[0]+".xml"));
         transformer.transform(new DOMSource(doc), new StreamResult(pw));
      }
      catch(Exception e) {
         e.printStackTrace();
      }
 
      System.exit(0);  // awt thread has been started
   }
 
   public static byte[] readBinaryFile(String filename)
                            throws IOException, FileNotFoundException {
      File f = new File(filename);         
      BufferedInputStream bis = new BufferedInputStream(
                                      new FileInputStream(f));         
      byte[] buffer = new byte[(int) f.length()];         
      bis.read(buffer, 0, buffer.length);         
      bis.close();
 
      return buffer;
   }
}

XML2Image.java:

import org.w3c.dom.*;
import org.w3c.dom.traversal.*;
  
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
  
import javax.swing.*;
import java.awt.*;
import java.io.*;
   
public class XML2Image
{
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java XML2Image <xml>");
         System.exit(1);
      }
 
      Document doc;
      try {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         DocumentBuilder db = dbf.newDocumentBuilder();
         doc = db.parse(new File(args[0]));
 
         Node root = doc.getFirstChild();  
         NodeList nl = root.getChildNodes();
          
         String format="", width="", height="", data="";
         for (int i=0; i<nl.getLength(); i++) {
            Node item = nl.item(i);
            Node text = item.getFirstChild();
            if (item.getNodeName().equals("format"))      format = text.getNodeValue();
            else if (item.getNodeName().equals("width"))  width  = text.getNodeValue();
            else if (item.getNodeName().equals("height")) height = text.getNodeValue();
            else if (item.getNodeName().equals("data"))   data   = text.getNodeValue();
         }
 
         System.out.println("Image width = " + width + ", height = " + height);
 
         byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(data);
 
         BufferedOutputStream bos = new BufferedOutputStream(
                                           new FileOutputStream(args[0]+"."+format));
         bos.write(b);
         bos.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   } 
}