Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
696 views
in Technique[技术] by (71.8m points)

c# - How to serialize a Class contains BitmapImage?

I have a DeepCopy method, which serializes the object passed in parameter and returns back the deserialized object to make deep copy.

My method is:

public static class GenericCopier<T>
{     
           public static T DeepCopy(object objectToCopy)
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(memoryStream, objectToCopy);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                    return (T)binaryFormatter.Deserialize(memoryStream);
                }
            }
}

It works well, if the object passed to the parameter doesn't contain any BitmapImage Field and Properties.

public class MyClass
{
  public string TestString {get; set;}
  public BitmapImage TestImage { get; set;}
}

If I make DeepCopy of MyClass,

MyClass orginal = new MyClass(){ TestString = "Test"};
MyClass copy = GenericCopier<MyClass>.DeepCopy(orginal);

it throws exception

Type 'System.Windows.Media.Imaging.BitmapImage' in Assembly is not marked as serializable

I found a method to serialize BitmapImage here

But, How can i mix the both type of serialization (BinaryFormatter & PngBitmapEncoder) to serialize MyClass?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have two options here:

Option 1: Implement ISerializable and Snapshot to PNG

What you must do here is have all classes that contain your BitmapImage implement the ISerializable interface, then, in GetObjectData, return a byte array representing an encoding of the image, for instance PNG. Then in the deserialization constructor decode the PNG to a new BitmapImage.

Note that this snapshots the image and thus may lose some WPF data.

Since you may have multiple classes that contain a BitmapImage, the easiest way to do this is to introduce some wrapper struct with an implicit conversion from and to BitmapImage, like so:

[Serializable]
public struct SerializableBitmapImageWrapper : ISerializable
{
    readonly BitmapImage bitmapImage;

    public static implicit operator BitmapImage(SerializableBitmapImageWrapper wrapper)
    {
        return wrapper.BitmapImage;
    }

    public static implicit operator SerializableBitmapImageWrapper(BitmapImage bitmapImage)
    {
        return new SerializableBitmapImageWrapper(bitmapImage);
    }

    public BitmapImage BitmapImage { get { return bitmapImage; } }

    public SerializableBitmapImageWrapper(BitmapImage bitmapImage)
    {
        this.bitmapImage = bitmapImage;
    }

    public SerializableBitmapImageWrapper(SerializationInfo info, StreamingContext context)
    {
        byte[] imageBytes = (byte[])info.GetValue("image", typeof(byte[]));
        if (imageBytes == null)
            bitmapImage = null;
        else
        {
            using (var ms = new MemoryStream(imageBytes))
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = ms;
                bitmap.EndInit();
                bitmapImage = bitmap;
            }
        }
    }

    #region ISerializable Members

    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
        byte [] imageBytes;
        if (bitmapImage == null)
            imageBytes = null;
        else
            using (var ms = new MemoryStream())
            {
                BitmapImage.SaveToPng(ms);
                imageBytes = ms.ToArray();
            }
        info.AddValue("image", imageBytes);
    }

    #endregion
}

public static class BitmapHelper
{
    public static void SaveToPng(this BitmapSource bitmap, Stream stream)
    {
        var encoder = new PngBitmapEncoder();
        SaveUsingEncoder(bitmap, stream, encoder);
    }

    public static void SaveUsingEncoder(this BitmapSource bitmap, Stream stream, BitmapEncoder encoder)
    {
        BitmapFrame frame = BitmapFrame.Create(bitmap);
        encoder.Frames.Add(frame);
        encoder.Save(stream);
    }

    public static BitmapImage FromUri(string path)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = new Uri(path);
        bitmap.EndInit();
        return bitmap;
    }
}

Then use it as follows:

[Serializable]
public class MyClass
{
    SerializableBitmapImageWrapper testImage;

    public string TestString { get; set; }
    public BitmapImage TestImage { get { return testImage; } set { testImage = value; } }
}

public static class GenericCopier
{
    public static T DeepCopy<T>(T objectToCopy)
    {
        using (MemoryStream memoryStream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(memoryStream, objectToCopy);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return (T)binaryFormatter.Deserialize(memoryStream);
        }
    }
}

Option 2: Use Serialization Surrogates to Clone the BitmapImage Directly

It turns out that BitmapImage has a Clone() method, so it is reasonable to ask: is it somehow possible to override binary serialization to replace the original with a clone, without actually serializing it? Doing so would avoid the potential data loss of snapshotting to PNG and would thus appear preferable.

In fact, this is possible using serialization surrogates to replace the bitmap images with an IObjectReference proxy containing an ID of a cloned copy created by the surrogate.

public static class GenericCopier
{
    public static T DeepCopy<T>(T objectToCopy)
    {
        var selector = new SurrogateSelector();
        var imageSurrogate = new BitmapImageCloneSurrogate();
        imageSurrogate.Register(selector);

        BinaryFormatter binaryFormatter = new BinaryFormatter(selector, new StreamingContext(StreamingContextStates.Clone));

        using (MemoryStream memoryStream = new MemoryStream())
        {
            binaryFormatter.Serialize(memoryStream, objectToCopy);
            memoryStream.Seek(0, SeekOrigin.Begin);
            return (T)binaryFormatter.Deserialize(memoryStream);
        }
    }
}

class CloneWrapper<T> : IObjectReference
{
    public T Clone { get; set; }

    #region IObjectReference Members

    object IObjectReference.GetRealObject(StreamingContext context)
    {
        return Clone;
    }

    #endregion
}

public abstract class CloneSurrogate<T> : ISerializationSurrogate where T : class
{
    readonly Dictionary<T, long> OriginalToId = new Dictionary<T, long>();
    readonly Dictionary<long, T> IdToClone = new Dictionary<long, T>();

    public void Register(SurrogateSelector selector)
    {
        foreach (var type in Types)
            selector.AddSurrogate(type, new StreamingContext(StreamingContextStates.Clone), this);
    }

    IEnumerable<Type> Types
    {
        get
        {
            yield return typeof(T);
            yield return typeof(CloneWrapper<T>);
        }
    }

    protected abstract T Clone(T original);

    #region ISerializationSurrogate Members

    public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
    {
        var original = (T)obj;
        long cloneId;
        if (original == null)
        {
            cloneId = -1;
        }
        else
        {
            if (!OriginalToId.TryGetValue(original, out cloneId))
            {
                Debug.Assert(OriginalToId.Count == IdToClone.Count);
                cloneId = OriginalToId.Count;
                OriginalToId[original] = cloneId;
                IdToClone[cloneId] = Clone(original);
            }
        }
        info.AddValue("cloneId", cloneId);
        info.SetType(typeof(CloneWrapper<T>));
    }

    public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
    {
        var wrapper = (CloneWrapper<T>)obj;
        var cloneId = info.GetInt64("cloneId");
        if (cloneId != -1)
            wrapper.Clone = IdToClone[cloneId];
        return wrapper;
    }

    #endregion
}

public sealed class BitmapImageCloneSurrogate : CloneSurrogate<BitmapImage>
{
    protected override BitmapImage Clone(BitmapImage original)
    {
        return original == null ? null : original.Clone();
    }
}

In this implementation, your main classes remain unchanged:

[Serializable]
public class MyClass
{
    BitmapImage testImage;

    public string TestString { get; set; }
    public BitmapImage TestImage { get { return testImage; } set { testImage = value; } }
}

Awkwardly, while BitmapImage has a Clone method, it does not actually implement the ICloneable interface. If it had, the code above could look cleaner, because we could simply clone every cloneable object rather than calling a specific method for BitmapImage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...