How to retrieve image to PictureBox in c# winforms? I tried this codes but I am having an argument exception saying that the parameter is not valid in my bitmap.
con = new SqlConnection(strConnection);
MemoryStream stream = new MemoryStream();
con.Open();
SqlCommand command = new SqlCommand(
"select companyLogo from companyDetailsTbl where companyId = 1", con);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
con.Close();
Bitmap bitmap = new Bitmap(stream); //This is the error
return bitmap;
A better way to do this:
using (SqlConnection con = new SqlConnection(strConnection))
using (SqlCommand cmd = new SqlCommand("select companyLogo from companyDetailsTbl where companyId = 1", con))
{
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
pictureBox1.Image = ByteArrayToImage((byte[])(reader.GetValue(0)));
}
}
}
public static Image ByteArrayToImage(byte[] byteArrayIn)
{
using (MemoryStream ms = new MemoryStream(byteArrayIn))
{
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}
Try using this:
byte[] image = (byte[])command.ExecuteScalar();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap = (Bitmap)tc.ConvertFrom(image);
Or:
byte[] image = (byte[])command.ExecuteScalar();
ImageConverter ic = new ImageConverter();
Image img = (Image)ic.ConvertFrom(image);
Bitmap bitmap = new Bitmap(img);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.