Ok, here is the thing. My program saves an image into a SQL Server Database, the column being of image type. When I try to recover it, I get an ArgumentException from the Imagen.FromStream method.
The code that inserts the image is something like this:
Bitmap img = (Bitmap)pictureBox.Image;
MemoryStream m = new MemoryStream();
img.Save(m, ImageFormat.Png);
try{
string query = "INSERT INTO Images (imgId, image) " +
"VALUES (1, @Img)"
byte[] imgByte = m.GetBuffer();
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("@Img", SqlDbType.Image)).Value = img;
cmd.ExecuteNonQuery();
} catch (Exception ex) {
//some code
} finally {
con.Close();
con.Dispose();
cmd.Dispose();
}
That seems to work fine, when I check the table it says it holds "Binary Data" (Probably there's a way to see the image, I don't know).
Now, here is the code that recovers the image:
string query = "SELECT image " +
"FROM Images " +
"WHERE imgId = 1";
bool ok;
try{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
byte[] imgByte = (byte[])cmd.ExecuteScalar();
MemoryStream m = new MemoryStream(imgByte);
ok = true
} catch (Exception ex) {
m = null;
} finally {
con.Close();
con.Dispose();
cmd.Dispose();
}
if (ok)
Bitmap img = new Bitmap(Image.FromStream(m)); //Here it throws the exception
I don't know much about image handling, so what you see is a mix of tutorials. That's also why I have no clue where the problem might be, and everything I found on the internet was kinda specific for each problem, so I couldn't apply that to mine.
Thanks for your time!