Kirk Evans is a Microsoft Architect for the Azure Center of Excellence.
Introduction to SharePoint and Azure IaaS
Building SharePoint Apps with Windows Azure Platform as a Service
SharePoint Solutions and Architectures on Windows Azure Infrastructure Services
Understanding Authentication and Permissions with Apps for SharePoint and Office
In a comment on my post on base64 decoding a picture in XML, someone asked (before the comment was deleted during the upgrade to Community Server until I learned where to find the comments in Community Server) how to do the opposite of that post. That is, how do you base64 encode binary data into an XML document?
The key to doing this lies in the XmlTextWriter.WriteBase64() method. This method accepts a byte array, so the only question left is how to convert a picture to a byte array?
In the example below, I load a GIF image from file into a System.Drawing.Image object. To convert this to a byte array, I save the picture to an in-memory stream, which in turn can be read into a byte array using the System.IO.Stream.ToArray() method. Once we have the byte array, we simply pass it to the XmlTextWriter.WriteBase64() method.
//Load the picture from a fileImage picture = Image.FromFile(@"c:\temp\test.gif");
//Create an in-memory stream to hold the picture's bytesSystem.IO.MemoryStream pictureAsStream = new System.IO.MemoryStream();picture.Save(pictureAsStream,System.Drawing.Imaging.ImageFormat.Gif);
//Rewind the stream back to the beginningpictureAsStream.Position = 0;//Get the stream as an array of bytesbyte  pictureAsBytes = pictureAsStream.ToArray();
//Create an XmlTextWriter to write the XML somewhere... here, I just chose//to stream out to the Console output streamSystem.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(Console.Out);
//Write the root element of the XML document and the base64 encoded datawriter.WriteStartElement("w","binData","http://schemas.microsoft.com/office/word/2003/wordml");
Note that I did not write out the complete Word 2003 XML document, I leave that as an exercise to the reader. The key part is seeing how to write the base64 encoded data to the w:binData element.