从数据库中获取图像

时间:2013-08-03 20:40:05

标签: c# winforms sql-server-2008

我有这段代码将图像从SQL Server 2008数据库显示到pictureBox

using (SqlCommand SqlCommand = new SqlCommand("Select * From Student Where StudentID = @a", myDatabaseConnection))
{
   SqlCommand.Parameters.AddWithValue("@a", SearchtextBox.Text);

   DataSet DS = new DataSet();

   SqlDataAdapter da = new SqlDataAdapter(SqlCommand);
   da.Fill(DS, "Images");

   dataGridView1.DataSource = DS.Tables[0];
   var imagesTable = DS.Tables["Images"];
   var imagesRows = imagesTable.Rows;
   var count = imagesRows.Count;

   if (count <= 0)
      return;

   var imageColumnValue = imagesRows[count - 1]["Image"];

   if (imageColumnValue == DBNull.Value)
      return;

   var data = (Byte[])imageColumnValue;

   using (var stream = new MemoryStream(data))
   {
       pictureBox1.Image = Image.FromStream(stream);
   }

但即使我将BackgroundImageLayout设置为拉伸

,它显示的图像也不会拉伸

我也试过这个:

using (var stream = new MemoryStream(data))
{
    pictureBox1.Image = Image.FromStream(stream);
    pictureBox1.BackgroundImageLayout = ImageLayout.Stretch; 
}

1 个答案:

答案 0 :(得分:1)

您的问题是在PictureBox.ImagePictureBox.BackgroundImage之间混淆了,所以您的代码应该是以下之一:

using (var stream = new MemoryStream(data))
{
  pictureBox1.BackgroundImage = Image.FromStream(stream);
  pictureBox1.BackgroundImageLayout = ImageLayout.Stretch; 
}

//or

using (var stream = new MemoryStream(data))
{
  pictureBox1.Image = Image.FromStream(stream);
  pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; 
}