3

如果用户不为图片框设置图像,我想在表中保存 empy 图像。

我的代码是:

 byte[] arrImage;
 if (picperson.Image != null)
 {
     //convert image to byte
     MemoryStream ms = new MemoryStream();
     picperson.Image.Save(ms, picperson.Image.RawFormat);
     arrImage = ms.GetBuffer();
     ms.Close();
 }
 else arrImage = null;

objcommand.Parameters.AddWithValue("@picture", arrImage);

当他添加空图像时, picperson.Image.Save(ms, picperson.Image.RawFormat); 行发生异常

如何将空图像添加到表中?


4

1 回答 1

1

You can't pass a null value for your image parameter, so a work around would be to send in a zero byte array:

if (picperson.Image != null) {
     //convert image to byte
} else {
 arrImage = new byte[0];
}

Unfortunately, that will not set the field to null.

To set the field to null would probably be handled best with a separate query, for example:

using (SqlCommand q = new SqlCommand("INSERT INTO M (MyImage) VALUES (null)", cn)
...

which does not use parameters.

As far as reading some of the comments are concerned, it sounds like the image format needs to be specified. Try using the actual format that you want the image saved as:

picperson.Image.Save(ms, ImageFormat.Bmp);
// or
picperson.Image.Save(ms, ImageFormat.Jpeg);  // or Png, etc.
于 2013-04-15T16:12:32.327 回答