Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add empty image to table

Tags:

c#

winforms

I want if user do not set image for picturebox save empy image in table .

my code is :

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

when he adds null image, exception occurs on line picperson.Image.Save(ms, picperson.Image.RawFormat);

How to add empty imag to table ?


like image 308
anfd Avatar asked Jan 17 '26 21:01

anfd


1 Answers

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.
like image 158
LarsTech Avatar answered Jan 20 '26 12:01

LarsTech