Storing an Image in an XML file
I recently had a project that required a custom subset of data from a database be stored in an XML file. Each “row” of data also had a related image on a separate server. The project required that both the data and the image be transferred to a client for subsequent consumption by another program. In designing the project, it seemed unnecessarily complex to transport the data and the images as separate entities. Mostly the problem was that this process would simply add more moving parts, which would add to the complexity and increase the probability of “user inspired difficulties.”
Since both the data and the images were to be consumed by the same process, it appeared logical to embed the Image objects directly in the XML file as part of the data description. I found several examples on the web and eventually hobbled together my own version.
Saving the Image to XML
Since XML is ultimately just a formatted text file, the first step is to find a way to represent the Image object as text.
Bitmap bmp = new Bitmap(imageFileName); TypeConverter converter = TypeDescriptor.GetConverter(typeof(Bitmap)); XElement img = new XElement("image", Convert.ToBase64String( (byte)converter.ConvertTo(bmp, typeof(byte)))); element.Add(img);
There are several things going on here. We want to convert the element to a byte so that we can extract a string representation of the object. To do this we create a TypeConverter object over the Bitmap type. Now we can use the TypeConverter to convert the Bitmap to a byte. Now, to properly encode the byte for writing to the XML file as a string, we convert it to a Base64 String.
Reading the Image from the XML file
Now that we have the Bitmap as part of our XML file, we need a way to read the Base64 String back into a Bitmap object:
string val = currentXml.Element("image").Value; byte bytes = Convert.FromBase64String(val); MemoryStream mem = new MemoryStream(bytes); Bitmap bmp2 = new Bitmap(mem);
In this example, we retrieve the XML text, convert it to a byte using Convert.FromBase64String(), use that to create a MemoryStream, and finally use the MemoryStream to create the Bitmap. Naturally, you can make this more concise:
Bitmap bmp = new Bitmap(new MemoryStream(Convert.FromBase64String(currentXml.Element("image").Value)));
Wrapping it up
I’m a novice when it comes to encryption and such things, so I’m not claiming that this is the best solution. It did work and the application is functioning as designed, but I’d like to get some feedback about this method, comments, alternatives, etc. If there is a problem with this solution or a better way to do it, please comment below.