I currently writing a program that creates and fills Controls in a WPF application from a XML file. One of the features are that the User can choose a image he wants to display in the program. This image is displayed in a Image Control. After choosing the image, the program saves all data back to the XML file.
The image is converted and saved as follows:
byte[] bytes = new byte[1];
MemoryStream ms = new MemoryStream();
System.Drawing.Image image = new Bitmap(sPathOfImage);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
bytes = ms.ToArray();
XElement Image = new XElement("Image", Convert.ToBase64String(bytes));
xDocument.Add(Image);
xDocument.Save("xDocument.xml");
And this works perfectly, all's fine. However, main problem is the length of the value of the XElement Image. Even for 40kb images the lenght is 60,000 signs. And for a 9mb image it needs huge 13,200,000 signs. And now I'm looking for a way better solution to store images in the XML file.
Through specifications it has to be in one XML file.
So, is there a good way to make the string smaller, a more suitable stream, anything I'm missing out? Any hint is appreciated.
One of the really cool features added to XMLSpy a few years ago based on customer requests is the ability to embed external files – such as images – directly in an XML document as encoded text. This gives you the option to package all required data from various external files together in one large XML document.
Scalable Vector Graphics (SVG)It may be included either by linkage, or by textual inclusion in an XML document that uses a different namespace. Because SVG can itself include raster images such as JPEG and PNG, SVG can be used to add raster and mixed vector/raster graphics to XML documents.
No magic will happen about filling an image content into XML file. The content will be proportional to the original file size. Even zipping the file and saving it to the XML will not help, because there are images with lower possibilities to be compressed. For evaluation purposes, I decided to find out how Visual Studio keeps the image in its resource file. The result is the following:
..
<data name="_myimage" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>Resources\myimage.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
</data>
Maybe would it make sense to stop reinventing the wheel, and believe the professionals? :)
To store image into XML file:
File.ReadAllBytes()
.Convert.ToBase64String()
To retrieve the image from XML file:
string val = currentXml.Element("image").Value;
byte[] bytes = Convert.FromBase64String(val);
MemoryStream mem = new MemoryStream(bytes);
Bitmap bmp2 = new Bitmap(mem);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With