Problem solve Get help with specific problems with your technologies, process and projects.

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;

Dig Deeper on .NET Framework development with XML and XAML

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.