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

心不动则不痛 提交于 2019-12-01 11:00:36

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!

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