Wednesday, March 21, 2007

Ok, lots of people have asked the question and I want to clear this up good and proper.   Here is how under Compact Framework 2, you can both insert images into a SQL Compact database and pull them out again.   This is particularly useful for putting camera images or signatures reliably (I feel the need to say reliably again), into and out the database.

Lots has been written about this, but comrades this really does work -

 

Today we'll do getting images out of the database and into a nice Bitmap variable.

To get an image from the database the only way I've found that works reliably

is using the ExecuteScalar like -

 

public Bitmap GetOurImage()

{

StringBuilder sbsql = new StringBuilder();
sbsql.Append("SELECT ");
sbsql.Append("[Picture] "); // This is an image field in the database
sbsql.Append("FROM ");
sbsql.Append("[SOME TABLE]");

 

object y = SqlQuickValue(sbsql.ToString()); // little helper function as I'm lazy
MemoryStream msimageblob = new MemoryStream((byte[])y);
Bitmap picture = new Bitmap(msimageblob);
msimageblob.Close();

return picture;

}

 

protected object SqlQuickValue(string strsql)
{

SqlCeCommand cmd = null;
object ret = null;

try
{
cn.Open();
cmd = new SqlCeCommand(strsql, cn); // note cn - is a sqlceconnection object
cmd.CommandType = CommandType.Text;
}
catch
{
if (cmd != null) cmd.Dispose();
cn.Close();
return ret;
}

try
{
ret = cmd.ExecuteScalar();
}
catch (SqlCeException e)
{
}
finally
{
cmd.Dispose();

}

cn.Close();
return ret;
}

 

Tomorrow, I'll show you how we can insert records into the database.

Thursday, March 22, 2007 2:37:09 PM UTC
The Bitmap constructor that takes a Stream requires that the stream be open for the lifetime of the Bitmap object. Closing the MemoryStream before returning the Bitmap is a bad idea. You need to keep them both in scope while you are using the Bitmap.
Thursday, March 22, 2007 3:00:03 PM UTC
Thanks Bryan.

Although I haven't seen any problems with the Compact Framework doing it this way.

http://support.microsoft.com/?id=814675

Tells me otherwise. The stream needs to be in scope, for the lifetime of the bitmap.

I've updated original source, just to make sure I'm giving out the best advice.
Richard
Comments are closed.

Theme design by Jelle Druyts

Pick a theme: