Datacontract序列化/序列化与图像 [英] Datacontract serialization/serialization with images
问题描述
我有一个带有图像的类,必须(有时)根据图像是否嵌入这一事实进行序列化/反序列化。
I have a class with an image that has to be (sometimes) serialized/deserialized according to the fact that the image is embedded or not.
[DataContract(IsReference = true)]
public class Data
{
[DataContract(IsReference = true)]
public class MyImage
{
[DataMember]
int WidthStorage
[DataMember]
int HeightStorage;
[DataMember]
public string strImageLocation;
[DataMember]
public Image ImageEmbedded = new Image();<----- not working null
public bool GetImage(Image image, int width, int height)
{
...
}
public void SetImageFSlocation(string _strImageLocation, int _widthStorage, int _heightStorage)
{
...
}
public void SetImageEmbedded(string strPathFilename, int _widthStorage, int _heightStorage)
{
...
}
}
所以问题在于尽管提出
public Image ImageEmbedded = new Image();
ImageEmbedded始终为null。
所以我把它放在一个构造函数中,如
ImageEmbedded is always null. So I put it in a constructor like
[DataContract(IsReference = true)]
public class MyImage
{
public MyImage()
{
ImageEmbedded = new Image();
}
...
但是当我这样做时,我得到一个序列化错误。
那我该怎么办?
我不会将Image转换为byte []或其他。我选择了Datacontract序列化,因为我认为它可以对图像进行serilize。
谢谢
but when I do that I get a serialization error. So what have I got to do? I would NOT turn Image to byte[] or other. I have chosen Datacontract serialization for I thought that it could serilize images. Thank you
推荐答案
您的代码中存在一个主要问题:如果序列化图像,则在WPF中序列化系统.Windows.Controls.Image。所以简而言之,序列化控件是没有意义的。相反,你可能想要序列化一个 BitmapSource
但是这里再次无法序列化,所以你必须将它们转换为 byte []
已经说过了。
There is a major problem in your code: in WPF if you serialize an Image you serialize System.Windows.Controls.Image. So in short it doesn't make sense to serialize a control. Instead you might want to serialize a BitmapSource
but here again those can't be serialized so you have to turn them to byte[]
as already said.
[DataMember]
public byte[] bytesBitmapEmbedded;
然后只需将其更改为BitmapSource或byte []:
and then simply change it to BitmapSource or byte[] through this:
bytesBitmapEmbedded = Converter.BitmapSource2ByteArray(bitmapSource);
或
bitmapSource = Converter.ByteArray2BitmapSource(bytesBitmapEmbedded);
with
public static class Converter
{
public static byte[] BitmapSource2ByteArray(BitmapSource bitmap)
{
using (var stream = new MemoryStream())
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
encoder.Save(stream);
return stream.ToArray();
}
}
public static BitmapSource ByteArray2BitmapSource(byte[] buffer)
{
using (var stream = new MemoryStream(buffer))
{
return BitmapFrame.Create(stream,
BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
}
这篇关于Datacontract序列化/序列化与图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!