在c#winforms中从数据库中检索图像到图片框

时间:2014-09-19 14:41:04

标签: c# winforms

如何在c#winforms中将图像检索到PictureBox?我尝试了这些代码,但我有一个参数异常,说该参数在我的位图中无效。

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;

2 个答案:

答案 0 :(得分:2)

更好的方法:

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;
    }
}

答案 1 :(得分:1)

尝试使用:

byte[] image = (byte[])command.ExecuteScalar();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap = (Bitmap)tc.ConvertFrom(image);

或者:

byte[] image = (byte[])command.ExecuteScalar();
ImageConverter ic = new ImageConverter();
Image img = (Image)ic.ConvertFrom(image);
Bitmap bitmap = new Bitmap(img);