如何从数据库中将图像显示到图片框中?

时间:2015-10-09 05:22:47

标签: c#

我使用了以下代码。

foreach (DataRow dr1 in dt.Rows)
{
   picbyte = (byte[])dr1["AssociateImageData"];
   Stream stream = new MemoryStream(picbyte);
   pictureBox1.Image =Image.FromStream(stream,true,true);
}

4 个答案:

答案 0 :(得分:1)

试试这样:

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

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

答案 1 :(得分:1)

试试这个,它对我有用:

private void viewSnapShotButton_Click(object sender, EventArgs e)
{
    this.Cursor = Cursors.WaitCursor;
    string connectionString = ConfigurationManager.AppSettings["myCconnectionSstring"];

    string queryString = ConfigurationManager.AppSettings["MyQueryString"];
    MemoryStream stream = new MemoryStream();
    SqlConnection connection = new SqlConnection(connectionString);
    try
    {
        connection.Open();
        SqlCommand command = new SqlCommand(queryString, connection);
        byte[] image = (byte[])command.ExecuteScalar();
        MemoryStream ms1 = new MemoryStream(image);
        exceptionPictureBox.Image = Bitmap.FromStream(ms1);  //this is how it should be.  I was using Image.FromStream and was getting error.
    }
    finally
    {
        connection.Close();
        stream.Close();
    }
    this.Cursor = Cursors.Default;
}

答案 2 :(得分:0)

foreach (DataRow dr1 in dt.Rows)
{
   picbyte = (byte[])dr1["AssociateImageData"];
   MemoryStream ms1 = new MemoryStream(picbyte);
   pictureBox1.Image = Bitmap.FromStream (ms1);
}

答案 3 :(得分:0)

这可能是最干净的解决方案,实际上可以正确清理内存。

using (var conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (var comm = new SqlCommand(queryString, conn)
    {
        using (var ms = new MemoryStream((byte[])comm.ExecuteScalar()))
        {
            pictureBox1.Image = Image.FromStream(ms);
        }
    }
}

如果要指定列或使用行中的其他列,也可以这样做。

using (var conn = new SqlConnection(connectionString))
{
    conn.Open();
    using (var comm = new SqlCommand(queryString, conn)
    {
        using (var reader = new comm.ExecuteReader())
        {
            if (reader.Read())
            {
                using (var ms = new MemoryStream((byte[])reader["Column"]))
                {
                    pictureBox1.Image = Image.FromStream(ms);
                }
            }
        }
    }
}