Save WPF Ink Strokes To a Database

by jason 20. December 2008 13:23

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.

Tags: , , ,

Development | WPF

Comments (4) -

Markus
Markus
7/20/2010 4:06:26 AM #

hi, is there a way to display the saved StrokeCollection in Silverlight?
(i have played around a lot, i doesnt get a clue) I cant make a StrokeCollection out of the memory stream!

Thanks in advice

jason
jason
7/20/2010 4:16:52 AM #

Unfortunately, I haven't tried any of this in Silverlight. However, I would guess that you could create the StrokeCollection object in your service and return it (I think it's serializable) back to the Silverlight client.
If you figure it out, please post back here as I'm now curious about this, too.
Thanks.
-Jason

Alicia Mundo
Alicia Mundo
9/19/2010 7:39:38 PM #

Hi,

I would like to know if there's a way to save stroke collection only?
Regardless if the ink canvas contains other elements such as text or image, just the stroke.

Thanks.

sandwich
sandwich
4/14/2011 2:42:33 AM #

Thank you

Comments are closed

About

Jason Williams is a .NET developer in Lincoln, Nebraska.

The name "Centrolutions" came out of a long search for a domain name. The goal was to create a name that conveyed an ideology of writing software centered (Centr--) on a solution (--olutions) for a particular problem. In other words, it was the only name in a long list that wasn't already registered on the internet.

If you're looking for the products I have for sale, you should go here.

Page List