问题
This is a further question about this topic: How to use deserialized object? I have a Problem with some variables in my class, right now I just put [XmlIgnore] infront of the variables wich cannot be serialized, so the serialazation of the class works for now.
My class looks like this:
public class Channel : INotifyPropertyChanged
{
public int Width { get; set; }
public int Height { get; set; }
[XmlIgnore]
public BitmapImage Logo { get; set; }
public string CurrentCoverURL { get; set; }
[XmlIgnore]
public SolidColorBrush Background { get; set; }
private string name;
public string Name
{
get { return name; }
set
{
name = value;
NotifyPropertyChanged("Name");
}
}
}
Now I somehow need to serialize the Bitmapimage and the SolidColorBrush too, so I can pass these informations to my next view.
I found a way to do this(Serialize a Bitmap in C#/.NET to XML), but this doesn't work for Windows 8 Apps. System.Drawing.Bitmap is not available in Windows 8.
Can someone help me with this issue?
Thanks!
回答1:
This helped me do the same thing. Just convert to a byte array first.
http://jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/
You can include your image in your JSON payload like this:
public class Person
{
public Int32 PersonId { get; set; }
public String FirstName { get; set; }
public byte[] Image { get; set; }
}
or you can include the imageUri in your JSON payload like this:
public class Person
{
public Int32 PersonId { get; set; }
public String FirstName { get; set; }
public String ImageUri { get; set; }
}
And you can convert your bitmapimage to a byte array like this;
public static byte[] ConvertToBytes(BitmapImage bitmapImage)
{
using (var ms = new MemoryStream())
{
var btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
// write an image into the stream
btmMap.SaveJpeg(ms, bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
return ms.ToArray();
}
}
回答2:
Your best bet is to stop serializing implementation (such as BitmapImage, SolidColorBrush, etc), are start serializing data. For example, if you want to transfer an image such as a jpg, gif, etc: a byte[] works remarkably well, and will be understood by most serializers. If you want to serialize a color - then you have various options:
- an enum
- an RGBA value (could be an
intor astring)
etc. This will work fine on virtually any serializer and platform. Then you simply process that data in the relevant way for your target platform.
回答3:
"I found a way to do this(Serialize a Bitmap in C#/.NET to XML), but this doesn't work for Windows 8 Apps. System.Drawing.Bitmap is not available in Windows 8."
You can use the BitmapImage.StreamSource for saving/CopyTo it to a MemoryStream and converting it to a bytearray
来源:https://stackoverflow.com/questions/18459620/serializing-object-containing-bitmapimage