Quick question:
What do I do if the user decided not to choose an image?
I have an Access 2007 database that can store an image using your code, the image is optional. If the user decides not to choose an image then I don't know what to store in the database.
In the GUI I have a Picturebox that shows the image the user has chosen. They use an OpenFileDialog to choose an image location, and I then set the ImageLocation property of the PictureBox to that path.
Then, when saving, I take the Image property of the PictureBox directly as the Image object you use in your code.
But when the user did not chose an image, the Image is null.
I am using this code to load:
csharp Code:
private Image LoadImage(byte[] picData) { Image pic = null; using (MemoryStream stream = new MemoryStream(picData)) { pic = Image.FromStream(stream); } return pic; }
And I am using this code to save:
(The @foto parameter will always be present in the sql that I pass to this function.)csharp Code:
public void ExecuteNonQuery(string sql, Image pic) { if (this.IsOpen()) { using (OleDbCommand cmd = new OleDbCommand()) { cmd.Connection = _connection; cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = sql; using (MemoryStream stream = new MemoryStream()) { cmd.Parameters.Clear(); if (pic != null) { pic.Save(stream, ImageFormat.Jpeg); cmd.Parameters.Add("@foto", OleDbType.Binary).Value = stream.GetBuffer(); } else { // what to do? cmd.Parameters.Add("@foto", OleDbType.Binary).Value = new byte[] {}; } } cmd.ExecuteNonQuery(); } } else { throw new Exception(strNO_DB_CONNECTION); } }
I tried various things for the value of the @foto parameter:
- null
- 0
- new byte[] {}
- simply stream.GetBuffer() as if there was a picture.
None of them work. I keep getting an exception "Parameter is not valid." on the Image.FromStream method in the Load function...
I can't simply not save it when the user didn't chose an image, because it is possible for the user to edit a record and remove the image that was previously chosen. So if I don't do anything that change wouldn't be recorded as the old image would still be in the database.
To fix this I can check if the picData array has zero length. That works when I simply store stream.GetBuffer on a new (empty) stream, but I'm not really sure if that's the 'accepted' way of doing it. What am I storing in the database in that case?




Reply With Quote