In my previous post about creating a bitmap from an InkCanvas in WPF, I mentioned that you could easily save the ink strokes for later. I wanted to post a code example for writing those strokes to a database and de-serialized them back into memory.
The first step in saving to a database is to get an array of bytes from the strokes in the InkCanvas. To do this, the StrokeCollection provides a convenient Save method:
byte[] signature; using (MemoryStream ms = new MemoryStream()) { icSignature.Strokes.Save(ms); signature = ms.ToArray(); } string sql = "INSERT INTO tblMyTable (mySigCol) VALUES (@Sig)"; SqlCommand comm = new SqlCommand(sql, conn); comm.Parameters.AddWithValue("@Sig", signature); comm.ExecuteNonQuery();
You can just as easily load the contents back from the database by creating a new stroke collection from the bytes save in the database:
string sql = "SELECT TOP 1 mySigCol FROM tblMyTable"; SqlCommand comm = new SqlCommand(sql, conn); byte[] signature = (byte[])comm.ExecuteScalar(); using (MemoryStream ms = new MemoryStream(signature)) { icSignature.Strokes = new System.Windows.Ink.StrokeCollection(ms); ms.Close(); }
If you need to persist a signature or annotation from an InkCanvas to a database and back, the process is very simple and makes the InkCanvas even more useful.