title: XSLT: Convert base64 data into image files
body: <p>I have seen several questions on how to encode an image file in base64, but how about the other way around - how do I reconstitute a picture from a base64 string stored in an XML file?</p>
  
  <pre><code>&lt;resource&gt;
  &lt;data encoding="base64"&gt;
  R0lGODlhEAAQAPMAMcDAwP/crv/erbigfVdLOyslHQAAAAECAwECAwECAwECAwECAwECAwECAwEC
  AwECAyH/C01TT0ZGSUNFOS4wGAAAAAxtc09QTVNPRkZJQ0U5LjAHgfNAGQAh/wtNU09GRklDRTku
  MBUAAAAJcEhZcwAACxMAAAsTAQCanBgAIf8LTVNPRkZJQ0U5LjATAAAAB3RJTUUH1AkWBTYSQXe8
  fQAh+QQBAAAAACwAAAAAEAAQAAADSQhgpv7OlDGYstCIMqsZAXYJJEdRQRWRrHk2I9t28CLfX63d
  ZEXovJ7htwr6dIQB7/hgJGXMzFApOBYgl6n1il0Mv5xuhBEGJAAAOw==
  &lt;/data&gt;
  &lt;mime&gt;image/gif&lt;/mime&gt;
  &lt;resource-attributes&gt;
      &lt;file-name&gt;clip_image001.gif&lt;/file-name&gt;
  &lt;/resource-attributes&gt;
  &lt;/resource&gt;
  </code></pre>
  
  <p>Given the above XML node <code>resource</code>, how do I go about creating <code>clip_image001.gif</code>?</p>
  
  <p>Please suggest:</p>
  
  <ol>
  <li>XSLT processors and/or extensions enable this, plus</li>
  <li>a sample XSLT that triggers the
  conversion</li>
  </ol>
  
  <p>Note that it must be able to handle at least GIF &amp; PNG file formats. Preferably not restricted to any OS.</p>
  
  <hr />
  
  <h1>Implemented solution</h1>
  
  <p>Based around <a href="https://stackoverflow.com/users/14419/mads-hansen">Mads Hansen's</a> solution. Main difference being that I referenced <code>net.sf.saxon.value.Base64BinaryValue</code> directly in my namespace rather than using the <code>saxon</code> namespace, because I understood the Java APIs more intuitively than the Saxonica website's descriptions of the <code>base64Binary-to-octets</code> and <code>base64Binary</code> functions.</p>
  
  <pre><code>&lt;xsl:stylesheet version="2.0" 
      xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:b64="net.sf.saxon.value.Base64BinaryValue"
      xmlns:fos="java.io.FileOutputStream"
      ...
      exclude-result-prefixes="b64 fos"&gt;
  ...
  &lt;xsl:for-each select="resource"&gt;                
      &lt;xsl:variable name="b64" select="b64:new(string(data))"/&gt;
      ...
      &lt;xsl:variable name="fos" select="fos:new(string($img))"/&gt;
      &lt;xsl:value-of select="fos:write($fos, b64:getBinaryValue($b64))"/&gt;  
      &lt;xsl:value-of select="fos:close($fos)"/&gt;
  &lt;/xsl:for-each&gt;
  ...
  </code></pre>
  
  <p>P.S. See <a href="https://stackoverflow.com/questions/1684963/xslt-obtaining-or-matching-hashes-for-base64-encoded-data">sibling question</a> for my implementation of how to obtain the hashes necessary to identify the image files.</p>
  
  <p><hr />
  This question is  a subquestion of <a href="https://stackoverflow.com/questions/1642104/evernote-export-format-enex-to-html-including-pictures">another question I have asked previously</a>.</p>