0

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: 'Self referencing loop detected for property 'Owner' with type 'System.Windows.Forms.PictureBox'. Path 'AccessibilityObject'.'"

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);
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
  • Did you ignore "Reference Loop Handling"? ```JsonConvert.SerializeObject(bagPicture1, new JsonSerializerSetting(){ ReferenceLoopHandling = ReferenceLoopHandling.Ignore })``` – Cotur Dec 30 '19 at 16:19
  • @Cotur i still get an error that it cant serialize the cursor. `Custom cursors cannot be converted to string` maybe SerializeObject for pictureBox is just possible in design time mode? – Charles Dec 30 '19 at 16:31
  • 4
    Don't serialize windows controls, just serialize the content of the control (in this case, the `Image`). Do you need to preserve other properties as well, like size/position, etc? – Ron Beyer Dec 30 '19 at 16:34

1 Answers1

1

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());

Restore the img:

var myBytes = JsonConvert.DeserializeObject<byte[]>(serialized);
var img = Bitmap.FromStream(new MemoryStream(myBytes));
Charles
  • 2,721
  • 1
  • 9
  • 15
  • 1
    This can work (IMO, you should mention that the Image is then deserialized to a byte array, to make the answer more useful), but don't use `ImageFormat.Jpeg`, use `ImageFormat.Png` (or nothing): Jpeg is a lossy compression, the image won't be the same when deserialized (even if not immediately noticeable, if the image doesn't represent areas of uniform colors). PNG will better preserve the color informations (you'll also avoid exceptions, in some specific cases). – Jimi Dec 30 '19 at 22:38