Method to serialize a class which contain BitmapImage : using 2 inherited class?

别来无恙 提交于 2019-12-01 08:06:02

问题


When my application closes, I want to serialize some data to make it persistent for the next use of the application. I choose to serialize these data with Newtonsoft.JsonConverter. But, I have a BitmapImage in my class, and it can't be serialized.

I'm bit stuck on this because I don't find a solution to keep my BitmapImage into my class (I need to keep it here) and being able to serialize this class. I tried to create a inherited class which contains the BitmapImage, but I'm not allowed to create an implicit operator from my base class.

I want to have an object in my class which can be used to be a source for a Image binding, and be able to serialize this class.


回答1:


I would suggest just "Saving the BitMap to a file" and serializing the image file name only.

But, if you must serialize the bitmap, just save the bitmap to a MemoryStream as byte[].

byte[] byteArray;

using (MemoryStream stream = new MemoryStream()) 
{
        Image.Save(stream, ImageFormat.Bmp);
        byteArray = stream.ToArray();
}

Update:

Serialize your image via Image Path.

private string m_imagePath;

    public Image Image { get; private set; }

    public string ImagePath
    {
        get { return m_imagePath; }
        set 
        {
            m_imagePath = value;
            Image = Image.FromFile(m_imagePath);
        }
    }

Update:

[JsonObject(MemberSerialization.OptIn)]
public class MyClass
{
    private string m_imagePath;

    [JsonProperty]
    public string Name { get; set; }

    // not serialized because mode is opt-in
    public Image Image { get; private set; }

    [JsonProperty]
    public string ImagePath
    {
        get { return m_imagePath; }
        set
        {
            m_imagePath = value;
            Image = Image.FromFile(m_imagePath);
        }
    }
}

As you can see, you have a json object here, that has the Opt-In attribute, meaning you need to specify which properties are serialized.
This demo object has a Name property that is serialized, an ImagePath property that is serialized.
However, the Image property is not serialized.
When you deserialize the object the image will load because the ImagePath setter has the needed funcionality.

I hope this helped, I tested it, and it works.
Rate if you like. Good Luck!



来源:https://stackoverflow.com/questions/10783647/method-to-serialize-a-class-which-contain-bitmapimage-using-2-inherited-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!