Reputation: 49
I want to read Image file(png, jpg, etc). and save xml file, load image from xml.
but first. Deserialize throw System.InvalidOperationException.
second. I don't know below method is correct.
Scenario.
1. Open Image file from hdd.
2. Save document(text with image like 'SomeClass' in below source) in my application.
3. When save document, application will serialize SomeClass with image.
4. Rerun application, and load xml file.
5. then, show image in my application.
using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(@"C:\z.jpg")))
{
StreamReader sr = new StreamReader(ms);
someClass.ImageData = sr.ReadToEnd();
Xml.Serialize<SomeClass>(someClass, @"C:\z.xml");
}
SomeClass someClass = Xml.Deserialize<SomeClass>(@"C:\z.xml");
BitmapImage image = new BitmapImage();
image.BegineInit();
image.Source = ??
image.EndInit();
System.Windows.Controls.Image imageControl = new Image();
imageControl.Source = image;
this.Content = imageControl;
this is Serialize, Deserialize static method.
public static class Xml
{
public static void Serialize<T>(T data, string path)
{
XmlSerializer s = new XmlSerializer(typeof(T));
using (FileStream fs = new FileStream(path, FileMode.Create))
{
s.Serialize(fs, data);
}
}
public static T Deserialize<T>(string path)
{
XmlSerializer s = new XmlSerializer(typeof(T));
using (FileStream fs = new FileStream(path, FileMode.Open))
{
fs.Position = 0;
return (T)s.Deserialize(fs);
}
}
}
This is SomeClass
[Serializable]
public class SomeClass
{
public string ImageData { get; set; }
public string TextData { get; set; }
}
thank you.
Upvotes: 1
Views: 500
Reputation: 17448
You need to convert the binary image data to a string. You can use the Convert methods to handle that.
Edit note - Noticed you were reading all bytes into a memory stream and then reading them again from a stream reader. It would simplify the code to just read it directly and convert those bytes to Base64.
Example below.
someClass.ImageData = Convert.ToBase64String(File.ReadAllBytes(@"C:\z.jpg"));
Xml.Serialize<SomeClass>(someClass, @"C:\z.xml");
------------------
SomeClass someClass = Xml.Deserialize<SomeClass>(@"C:\z.xml");
BitmapImage image = new BitmapImage();
image.BegineInit();
image.Source = Convert.FromBase64String(someClass.ImageData);
image.EndInit();
Upvotes: 3