使用 JSON 序列化图片框 [英] Serializing a PictureBox with JSON

查看:27
本文介绍了使用 JSON 序列化图片框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 C# Windows 窗体应用程序项目,我需要使用 JSON 序列化 PictureBox 并将其保存到文件中.出于某种原因,JSON 在尝试序列化 PictureBox 时给我一个错误:

I'm working on a C# Windows Form app project where i need to serialize PictureBox with JSON and save it to a file. For some reason JSON is giving me an error when trying to serialize the PictureBox:

Newtonsoft.Json.JsonSerializationException:'检测到属性'Owner'的自引用循环,类型为'System.Windows.Forms.PictureBox'.路径'AccessibilityObject'.'"

"Newtonsoft.Json.JsonSerializationException: 'Self referencing loop detected for property 'Owner' with type 'System.Windows.Forms.PictureBox'. Path 'AccessibilityObject'.'"

我尝试创建一个新项目并在 PictureBox 上使用序列化,并且效果很好.我正在处理的当前项目可能会出现什么错误?

I tried to create a new project and use the serializing on a PictureBox and it worked fine. What could possibly give the error on the current project i'm working on?

string dataToSave = JsonConvert.SerializeObject(bagPicture1);

推荐答案

你可以像这样序列化 img:

You can serialize the img like this:

var img = this.pictureBox1.Image;
var ms = new MemoryStream();

// any ImageFormat you like, ImageFormat.Bmp for uncompressed
img.Save(ms, ImageFormat.Jpeg); 

var serialized = JsonConvert.SerializeObject(ms.ToArray());

恢复图片:

var myBytes = JsonConvert.DeserializeObject<byte[]>(serialized);
var img = Bitmap.FromStream(new MemoryStream(myBytes));

这篇关于使用 JSON 序列化图片框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆