i have stored jpeg images in database table. now i want to retrieve them. here is the code
MemoryStream stream = new MemoryStream();
try
{
cnn.Open();
cmd = new
SqlCommand("select pics from images", cnn);
byte[] image = (byte[])cmd.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);
Response.ContentType = "image/gif";
bitmap.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Bmp);
}
finally
{
cnn.Close();
stream.Close();
}
but when i run the application it gives me the following error
Parameter is not valid.
Bitmap bitmap = new Bitmap(stream);
can somebody tells me what i need to correct.
Loading

VulpesRank #55 · 29.2K reputationPosted Oct 26, 2011, 7:53 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 26, 2011, 3:48 AM EDT
saifullah khanRank #4,887 · 320 reputationPosted Oct 26, 2011, 5:59 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 26, 2011, 6:15 AM EDT
saifullah khanRank #4,887 · 320 reputationPosted Oct 26, 2011, 6:32 AM EDT
Parameter is not valid.
Image imag =Image.FromStream(stream);
Javeed M ShaikhRank #839 · 2.7K reputationPosted Oct 26, 2011, 6:36 AM EDT
what Vulpes is trying to say in his previous post is for you to check if you are doing the following when you are inserting the image in the database:
stream.Seek(0, SeekOrigin.Begin);
Please check the above in your image upload code.
saifullah khanRank #4,887 · 320 reputationPosted Oct 26, 2011, 6:41 AM EDT
protected void Button1_Click(object sender, EventArgs e)
{
int len = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[len];
FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
cnn.Open();
cmd = new SqlCommand("insert into images values('" + pic + "')", cnn);
cmd.ExecuteNonQuery();
}
here is the code for retriving from db.
protected void Page_Load(object sender, EventArgs e)
{
MemoryStream stream = new MemoryStream();
try
{
cnn.Open();
cmd = new SqlCommand("select pics from images", cnn);
byte[] image = (byte[])cmd.ExecuteScalar();
stream.Write(image, 0, image.Length);
Image imag =Image.FromStream(stream);
Response.ContentType = "image/gif";
imag.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Bmp);
}
finally
{
cnn.Close();
stream.Close();
}
VulpesRank #55 · 29.2K reputationPosted Oct 26, 2011, 6:53 AM EDT
saifullah khanRank #4,887 · 320 reputationPosted Oct 26, 2011, 7:08 AM EDT
Javeed M ShaikhRank #839 · 2.7K reputationPosted Oct 26, 2011, 7:17 AM EDT
Also did you try to add this line in the upload as suggested by Vulpes:
stream.Seek(0, SeekOrigin.Begin);
it should be like this in your code:
FileUpload1.FileContent.Seek(0, SeekOrigin.Begin);
FileUpload1.PostedFile.InputStream.Read(pic, 0, len);
saifullah khanRank #4,887 · 320 reputationPosted Oct 26, 2011, 7:47 AM EDT
its the output
saifullah khanRank #4,887 · 320 reputationPosted Oct 26, 2011, 8:05 AM EDT