Method to serialize a class which contain BitmapIm

2019-02-19 08:32发布

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条回答
smile是对你的礼貌
2楼-- · 2019-02-19 09:19

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!

查看更多
登录 后发表回答