首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >序列化PixelFormat

序列化PixelFormat
EN

Stack Overflow用户
提问于 2015-12-07 07:04:11
回答 1查看 189关注 0票数 0

我想序列化System.Windows.Media.PixelFormat对象,然后通过反序列化重新创建它。我在做什么:

代码语言:javascript
复制
BitmapSource bitmapSource = backgroundImage.ImageSource as BitmapSource;
PixelFormat pixelFormat = bitmapSource.Format;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("test", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, pixelFormat);
stream.Close();

然后

代码语言:javascript
复制
PixelFormat pixelFormat;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("test", FileMode.Open, FileAccess.Read, FileShare.Read);
pixelFormat = (PixelFormat)formatter.Deserialize(stream);
stream.Close();

序列化没有给出任何错误。当我尝试反序列化这个对象时,它也没有给出任何错误,但是返回的对象不是很好,例如在BitsPerPixel字段中它具有BitsPerPixel = 'pixelFormat.BitsPerPixel' threw an exception of type 'System.NotSupportedException'

@edit我有一个解决这个问题的办法。我们必须使用PixelFormatConverter将PixelFormat对象转换为字符串,然后序列化该字符串。在反序列化时,我们获得字符串,并使用PixelFormatConverter将其转换回PixelFormat。

EN

回答 1

Stack Overflow用户

发布于 2015-12-07 13:44:27

虽然System.Windows.Media.PixelFormat被标记为[Serializable],但它的每个字段都被标记为[NonSerialized]

这意味着当您试图反序列化对象时,这些字段不会正确地恢复为它们的原始值(也不会被初始化,而不是它们的默认值),从而使PixelFormat的反序列化值无效。当然,如果你试图检索它的BitsPerPixel,而它试图确定无效格式的每像素位数,你就会得到一个异常。

正如您已经发现的,将值序列化为string,然后在反序列化时进行转换。例如:

代码语言:javascript
复制
BitmapSource bitmapSource = backgroundImage.ImageSource as BitmapSource;
string pixelFormat = bitmapSource.Format.ToString();
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("test", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, pixelFormat);
stream.Close();

然后:

代码语言:javascript
复制
PixelFormat pixelFormat;
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("test", FileMode.Open, FileAccess.Read, FileShare.Read);
pixelFormat = (PixelFormat)new PixelFormatConverter()
    .ConvertFromString((string)formatter.Deserialize(stream));
stream.Close();

当然,您也可以自己显式地执行此操作,枚举PixelFormats中的属性并查找值(或者基于该类的成员构建Dictionary<string, PixelFormat> )。但是PixelFormatConverter很方便,可以做你想做的事情。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34123960

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档