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? 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");

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;

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();
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

Dig deeper on .NET Framework development with XML and XAML

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.



Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: