将SQL Server CE中的varbinary位图加载到picturebox中

时间:2013-08-27 14:15:47

标签: c# winforms bytearray sql-server-ce memorystream

我正在尝试将预先保存的图像从SQL Server CE VarBinary列加载到PictureBox

列内容是以varbinary格式存储的位图图像。

MemoryStream ms = new MemoryStream();
byte[] outbyte = new byte[100];
Int32 ordinal = 0;

conn.Open();
SqlCeDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
     ordinal = reader.GetOrdinal("FaceStamp");//FaceStamp: VarBinary column storing Bmp.
     outbyte = (byte[])reader[ordinal];
     ms.Write(outbyte, 0, outbyte.Length);
     ms.Seek(0, SeekOrigin.Begin);
     pictureBox1.Image = Image.FromStream(ms);
}          

conn.Close();

// Code below is the code I used to save the Bitmap image to the database
Bitmap bmi = cam.GetBitmap(); // Capture image from webcam which I've tested working.
ImageConverter converter = new ImageConverter();
byte[] byteArray = new byte[0];
byteArray = (byte[])converter.ConvertTo(bmi, typeof(byte[])); 
insert.Parameters.AddWithValue("@image", byteArray);
insert.ExecuteNonQuery();

我在以下行收到错误:

pictureBox1.Image = Image.FromStream(ms);

  

{“参数无效。”}

任何提示?

谢谢。

1 个答案:

答案 0 :(得分:0)

在转换保存为字节数组的图像时,我通常会执行以下操作:

byte[] outbyte = (byte[])reader[ordinal];
using (MemoryStream ms = new MemoryStream(outbyte))
{
    Bitmap image = new Bitmap(ms);
    pictureBox1.Image = image;
}

要将原始图像转换为字节数组,您可以查看this SO question