将数据从db显示到picturebox winforms c#

时间:2014-03-16 07:29:58

标签: c# sql winforms

我正在做一个winforms应用程序,将图像插入数据库(sql server 2008),并将数据库中的图像检索到图片框中。插入代码完美无缺。而用于检索显示的代码是错误参数not Valid.I正在尝试通过goggling找到的各种解决方案,但没有一个成功。

这是我的检索代码

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

        }

    }

3 个答案:

答案 0 :(得分:0)

试试这段代码:

存储到数据库中:

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;

答案 1 :(得分:0)

您可以这样做,

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

答案 2 :(得分:0)

首先,您必须考虑数据库中的数据类型必须是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);
}