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

本文关键字:数据库 c#winforms 检索 | 更新日期: 2023-09-27 18:23:40

如何在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;

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

更好的方法是:

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

尝试使用这个:

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