Ask the Expert

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

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: