显示图像从数据库到图片盒winforms c#

本文关键字:winforms 显示图 图像 数据库 显示 | 更新日期: 2023-09-27 17:50:32

我做一个winforms应用程序插入一个图像到数据库(sql server 2008),并从数据库检索图像到图片框。插入代码工作得很完美。而代码检索显示了一个错误参数无效。我试了各种各样的解决办法,但没有一个成功。

这是我的代码检索
           private void button2_Click(object sender, EventArgs e)
            {
 FileStream fs1 = new FileStream("D:''4usdata.txt", FileMode.OpenOrCreate,FileAccess.Read);
        StreamReader reader = new StreamReader(fs1);
        string id = reader.ReadToEnd();
        reader.Close();
        int ide = int.Parse(id);
        con.Open();
        SqlCommand cmd = new SqlCommand("select img from tempdb where id='" + id + "'", con);
        //cmd.CommandType = CommandType.Text;
        //object ima = cmd.ExecuteScalar();
        //Stream str = new MemoryStream((byte[])ima);
        //pictureBox1.Image = Bitmap.FromStream(str);
        SqlDataAdapter dp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        dp.Fill(ds);
        int c = ds.Tables[0].Rows.Count;
        if (c ==1)
        {

            Byte[] MyData = new byte[0];
            MyData = (Byte[])ds.Tables[0].Rows[0]["img"];
            MemoryStream stream = new MemoryStream(MyData);
            stream.Position = 0;
            pictureBox1.Image = Image.FromStream(stream);
        }
    }

显示图像从数据库到图片盒winforms c#

首先您必须考虑图像数据库中的数据类型必须是VarBinary:

在你的按钮点击事件:

byte[] getImg=new byte[0];
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select img from tempdb where id='" + id + "'", con);
cmd.CommandType=CommandType.Text;
DataSet ds = new DataSet();
da.Fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
   getImg=(byte[])dr["img"];
}
byte[] imgData=getImg;
MemoryStream stream = new MemoryStream(imgData);
pictureBox1.Image=Image.FromStream(stream);
}

试试下面的代码:

存储到数据库:

public byte[] WinImage=new byte[0];
MemoryStream stream = new MemoryStream();
PictureBox.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
WinImage=stream.ToArray();

并将其保存为varbinary(max)。

从数据库中检索图像:

MemoryStream stream = new MemoryStream(byte[] WinImage);
Image RetImage = Image.FromStream(stream);
PictureBox.Image = RetImage;

你可以这样做,

Byte[] MyData = new byte[0];
MyData = (Byte[])ds.Tables[0].Rows[0]["img"];
if (MyData != null && MyData .Length > 0)  
{
    string img = Convert.ToBase64String(MyData , 0, MyData.Length);
    pictureBox1.ImageUrl = "data:image/png;base64," + img;
}