Saturday, February 17, 2007

How to Serialise Image

I was reading in the CodeProject C# forum when a question gave me the idea for a simple article.

The poster wanted to read an image into a byte array and had posted some sample code.

This is a concept that some time ago, I created several test projects when I wanted test the posibility of storing objects in a database.

I looked upon the image as being just another object and thought that a similar technique could be applied and set about creating a sample project.

I followed the same steps as detailed in my reply:


1) Create a new windows form app
2) Add to the form 2x picture boxes, one named source, the other dest
3) Add a new button named serialise
4) Set the background image of the picturebox named source to whatever you want
(for testing, do this using the designer)

5) Add a handler to the buttons click event

(this normally happens automatically if you double click the button in the designer)

6) Add using System.Runtime.Serialization.Formatters.Binary; declaration to your class
7) Paste the following code:
  void SerialiseClick(object sender, EventArgs e)
{
//serialise the background image of the source
byte[] byteArray = Serialise( source.BackgroundImage );
//deserialise the background image into the dest
dest.BackgroundImage = (System.Drawing.Image)Deserialise(byteArray);
}

public static byte[] Serialise( object obj )
{
//instanciate a new memory stream
System.IO.MemoryStream ms = new System.IO.MemoryStream();
//instanciate a new BinaryFormatter
BinaryFormatter bf = new BinaryFormatter();
//serialise the object into the memory stream
bf.Serialize( ms, obj );
//return the memory stream as a byte array
return ms.ToArray();
}

public static object Deserialise( byte[] obj )
{
//read the object into a memory stream
System.IO.MemoryStream ms = new System.IO.MemoryStream( obj );
//instanciate a binary formatter
BinaryFormatter bf = new BinaryFormatter();
//return the deserialised byte array as an object
return bf.Deserialize(ms) ;
}
With any luck, when the application is run, the resulting form should look similar to the one as pictured bellow:



If the code was pasted correctly, clicking the 'Serialise' button should invove the buttons click method where:
  • the background of the source image is serialised into a byte array
  • the byte array is de-serialised into an image
  • the image is set as the background of the destination image
This should result in the image being displayed in the 'Serialised Image' picture box which would therfor look as follows:



The sample project can be downloaded from here: http://www.box.net/public/14kiat6na7

The original post can be viewed here: CodeProject C# Forum

No comments: