1

I'm trying to load a pre-saved images from an SQL Server CE VarBinary column into a PictureBox.

The column content is a bitmap image stored in varbinary format.

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();

I get an error at the following line:

pictureBox1.Image = Image.FromStream(ms);

Saying

{"Parameter is not valid."}

Any tips?

Thank you.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yousef Imran
  • 81
  • 1
  • 3
  • 9
  • Are you sure your `image` was saved into your database as `byte[]` correctly? At least you have to know how you convert the image into `byte[]` to convert back accordingly. – King King Aug 27 '13 at 14:21
  • Yes I checked the fields and I can see that it contains Binary data in there. – Yousef Imran Aug 27 '13 at 14:57
  • 1
    No, binary data doesn't mean it can be `converted` to an image that way. If you used `Serialization` to turn bitmap data into `byte[]`, you have to use `'Deserialization` to get it back from `byte[]`. – King King Aug 27 '13 at 15:04

1 Answers1

0

I usually do the following when converting images saved as byte arrays:

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

For converting the original image to a byte array you can take a look at this SO question.

Community
  • 1
  • 1
ThoBa
  • 505
  • 4
  • 8
  • I get the same error at line _Bitmap image = new Bitmap(ms)_ . – Yousef Imran Aug 27 '13 at 14:41
  • Did you follow the MemoryStream-example in the other SO question to save your image using System.Drawing.Imaging.ImageFormat.Bmp instead of Png? – ThoBa Aug 28 '13 at 07:42