从Db获取图像到图像框

时间:2017-05-03 08:18:13

标签: c#

这是我的代码我试图从db检索图像但参数在内存流上无效,并且看到很多关于参数的答案在stackoverflow上无效但我的问题是相同的

try
{
    con = new SqlConnection(cs.DBConn);
    con.Open();

    // Retrieve BLOB from database into DataSet.
    String sql = "Select  Image from Users where Username='" + TxtUserName.Text + "' and password='" + TxtPassword.Text + "'";
    cmd = new SqlCommand(sql, con);
    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        byte[] b = new byte[0];
        b = (Byte[])(dr["Image"]);
        MessageBox.Show(b.ToString());
        MemoryStream ms = new MemoryStream(b);
        pictureBox1.Image = Image.FromStream(ms);
        frm.pictureBox2.Image = pictureBox1.Image;

        con.Close();
    }
}
catch (Exception ex)
{ 
    MessageBox.Show(ex.Message);
}

3 个答案:

答案 0 :(得分:0)

尝试这样:

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
    var stream = new MemoryStream(data);
    pictureBox1.Image= Image.FromStream(sream);
} 

答案 1 :(得分:0)

Image myImage = null;
if (!(dr["Image"] is DBNull))
{
   byte[] b = (Byte[])(dr["Image"]);
   using (MemoryStream ms = new MemoryStream(b, 0, b.Length))
   {
        ms.Write(b, 0, b.Length);
        myImage = Image.FromStream(ms, true);
   }
}
pictureBox1.Image = myImage;

答案 2 :(得分:0)

虽然其他答案已经可以解决您手头的问题,但我还是建议进行一些额外的优化:

try
{
    // Put your connection into a using block to have closing/disposing handled for you
    using (con = new SqlConnection(cs.DBConn))
    {
        con.Open();

        // Create a query with placeholders for your parameter values
        // Limit it with TOP 1 - since you only expect to identify 1 user
        string sql = "SELECT TOP 1 [Image] FROM [Users] WHERE [Username] = @usr AND [password] = @pwd";

        using (cmd = new SqlCommand(sql, con))
        {
            // add a parameter with the user name value
            cmd.Parameters.AddWithValue("usr", TxtUserName.Text);

            // add a parameter with the password value
            cmd.Parameters.AddWithValue("pwd", TxtPassword.Text);

            // Use ExecuteScalar since you only expect 1 row with 1 column
            byte[] b = cmd.ExecuteScalar() as byte[];

            // you may want to check if byte array b is null

            // Same as for Connection: let using handle disposing your MemoryStream
            using (MemoryStream ms = new MemoryStream(b))
            {
                pictureBox1.Image = Image.FromStream(ms);
                frm.pictureBox2.Image = pictureBox1.Image;
            }
        }
    }
}
catch (Exception ex)
{ 
    MessageBox.Show(ex.Message);
}