Can we store an image in XML file, just like we store an image file as binary in SqlDatabase?

Can we store an image in XML file, just like we store an image file as binary in SqlDatabase?

Can we store an image in XML file, just like we store an image file as binary in SqlDatabase?

    Requires Free Membership to View

    When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to provide a unique online resource for developers, architects and development managers tasked with building and maintaining enterprise applications using Visual Basic, C# and the Microsoft .NET platform.

    Hannah Smalltree, Editorial Director

    By submitting your registration information to SearchWinDevelopment.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchWinDevelopment.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

Yes, you can. But as the XML file is a text file, any binary data has to be base64-encoded first. Recall that the encoded version will be approximately 1.5 times bigger than the raw binary data. One way to do this is as follows:

Suppose you have the following XML document:

XmlDocument doc = new XmlDocument();
//Create the document structure
XmlNode pics = doc.CreateElement("pictures");
XmlNode pic = doc.CreateElement("picture");
pics.AppendChild(pic);
doc.AppendChild(pics);

Next you read the binary file (in this case an image) and assign it to the XmlElement inner text:

//Read the bitmap.
string data = null;
Bitmap bmp = new Bitmap(@"e:Image.bmp");
using (MemoryStream mem = new MemoryStream())
{
	bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Bmp);
	//Convert the bytes to a string.
	data = Convert.ToBase64String(mem.ToArray());
}

//Save the data and the document.
pic.InnerText = data;
doc.Save(@"e:Image.xml");

To display the image in a PictureBox, you load the document, get the node text and perform the inverse procedure:

//Reload the document and display the image.
doc = new XmlDocument();
doc.Load(@"e:Image.xml");
data = doc.SelectSingleNode("/pictures/picture").InnerText;

using (MemoryStream mem = new MemoryStream(Convert.FromBase64String(data)))
{
	//Load the image from the stream.
	bmp = Bitmap.FromStream(mem) as Bitmap;
}
//Asign it to a PictureBox
pcImage.Image = bmp;

This was first published in May 2003