I have certain images in my sqlite3 database and I was trying to retrieve it into my windows application using .Net framework 4.5. For the following code, I am getting an error stating
An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: Parameter is not valid.
This always seems to occur due to the memory stream.
private void button1_Click(object sender, EventArgs e)
{
using( MemoryStream ms = new MemoryStream(GetImageFromDB(1), false))
{
Image dbImg = Image.FromStream(ms); //System.ArgumentException--Parameter Not Valid
dbImg.Save("Testing", System.Drawing.Imaging.ImageFormat.Png);
}
}
private byte[] GetImageFromDB(int ImgId)
{
byte[] btImage;
sql_con = new SQLiteConnection("Data Source=test.db; Version=3;New=False;Compress=True;");
string str = "select org_file_header_blob from file where _id = 1;";
sql_cmd = new SQLiteCommand(str, sql_con);
sql_con.Open();
btImage = (byte[])sql_cmd.ExecuteScalar();
sql_con.Close();
return btImage;
}
I have used a similar code before, and it has worked well. I have tried several methods to get rid of the error, but every time its the same. I have tried:
Getting it into a Bitmap object instead of an Image object using:
Bitmap dbImg = new Bitmap(ms);
and
...
sql_con.Close();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap1 = (Bitmap)tc.ConvertFrom(btImage);
bitmap1.Save("Testing", System.Drawing.Imaging.ImageFormat.Png);
...
I have even checked the length of btImg after the sql_con.Close()
using the btImg.length
command. It gives me 10 as the output. Which, if I assume is 10 bytes, would not make any sense since it is an image.
When I execute the same query in the sqlite3 database, I get
This is basically 2 blank lines which is where I assume is the image.
Any ideas on what I could possibly be missing?
Edit:
P.S. Just to clarify, I am trying to convert an existing byte[] into an image