Serialize and deserialize multiple images in files in C#

[serialize]

The example Serialize and deserialize multiple images in C# showed how you can List<Image> into a memory stream and then deserialize stream to recover the images. This example shows how you can similarly serialize a list of images into a file and then deserialize the list from that file.

This example actually includes two programs, one to serialize the images and one to deserialize them. I decided to do this in two programs to be certain that the serialization did not include the namespace of the serialization program. Some serialization methods include the serialized object’s namespace and that can make deserializing the objects harder. This example uses two programs to show that this isn’t an issue.

The previous example shows most of what you need to do to serialize and deserialize a list of images in a file. The following sections describe the key pieces of the two example programs included in the download.

Serialization


[serialize]

The howto_save_serialized_images example program displays three images that are placed in PictureBox controls at design time. When you open the File menu and select Save Serialization, the following code executes.

// Save a serialization of the images.
private void mnuFileSave_Click(object sender, EventArgs e)
{
    // Get the serialization file name.
    if (sfdSerialization.ShowDialog() == DialogResult.OK)
    {
        // Add the files to a list.
        List<Image> input_images = new List<Image>();
        input_images.Add((Bitmap)picSource1.Image);
        input_images.Add((Bitmap)picSource2.Image);
        input_images.Add((Bitmap)picSource3.Image);

        // Serialize.
        using (FileStream fs = new FileStream(
            sfdSerialization.FileName, FileMode.Create))
        {
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(fs, input_images);
        }
    }
}

This code displays a SaveFileDialog. If you enter a file name and click Save, the code creates a List<Image> and adds the three images to it.

Next, the program creates a FileStream to create the file. It makes a BinaryFormatter and uses its Serialize method to serialize the list of images into the FileStream.

When the using block ends, the program automatically closes the FileStream.

Deserialization


[serialize]

The howto_load_serialized_images example program lets you read the images in a serialization. When you open the File menu and select Open Serialization, the following code executes.

// Load a serialization.
private void mnuFileOpen_Click(object sender, EventArgs e)
{
    // Get the serialization file name.
    if (ofdSerialization.ShowDialog() == DialogResult.OK)
    {
        // Deserialize.
        using (FileStream fs = new FileStream(
            ofdSerialization.FileName, FileMode.Open))
        {
            BinaryFormatter formattter = new BinaryFormatter();
            List<Image> output_images =
                (List<Image>)formattter.Deserialize(fs);

            // Display the images.
            const int margin = 10;
            int x = margin;
            int y = menuStrip1.Bottom + 4;
            foreach (Image image in output_images)
            {
                PictureBox pic = new PictureBox();
                pic.Location = new Point(x, y);
                pic.SizeMode = PictureBoxSizeMode.AutoSize;
                pic.Image = image;
                pic.BorderStyle = BorderStyle.Fixed3D;
                pic.Parent = this;
                x += pic.Width;
            }
        }
    }
}

This code displays an OpenFileDialog. If you select a file and click Open, the code creates a FileStream attached to that file. It then makes a BinaryFormatter and uses its Deserialize method to read the serialization from the FileStream. It converts the result into a List<Image>.

Next, the program loops through the images in the list and displays them in a sequence of PictureBox controls.

Conclusion

That’s about all there is to the example programs that serialize and deserialize images. This is one of the rare instances when the download doesn’t contain much more than the code shown here. The only important things that are missing are the two following using directives.

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

Using the techniques demonstrated by these examples and the previous post, you should be able to serialize and deserialize a list of images in any stream, whether it’s a memory stream, file stream, or something else.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in database, files, serialization and tagged , , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to Serialize and deserialize multiple images in files in C#

  1. chico123 says:

    Hi Rod,
    the DL-Url …/howto_whatever.zip does’nt work.

  2. Thomas says:

    Download link is broken(404 error)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.