从SQL Server数据库中检索图像

时间:2011-07-24 08:10:40

标签: c# sql-server memorystream

我有一个问题,当我从内存流中检索数据库中的图像时,会出现错误Parameter is not valid。请帮我解决这个问题。

代码:

private void button3_Click(object sender, EventArgs e)
{
   string strcon = "Data Source=PINKAL-PC; initial catalog=testing; integrated security=SSPI;";

   SqlConnection sqlcon = new SqlConnection(strcon);
   sqlcon.Open();

   string strquery = "select * from testimg";

   SqlDataAdapter da = new SqlDataAdapter(strquery,sqlcon);
   DataSet ds = new DataSet();
   da.Fill(ds);

   DataTable dt = new DataTable();
   dt = ds.Tables[0];

   byte[] barrImg = (byte[])dt.Rows[7]["image"];
   MemoryStream mstream = new MemoryStream(barrImg);

   pictureBox2.Image = Image.FromStream(mstream);
}

2 个答案:

答案 0 :(得分:2)

不确定问题的根本原因是什么 - 我的猜测是数据库表image中没有testimg名称的列,但您正在尝试阅读那列可以得到你的照片。

但是我会为你的代码推荐一些事情:

private void button3_Click(object sender, EventArgs e)
{
   string strcon = "Data Source=PINKAL-PC; initial catalog=testing; integrated security=SSPI;";

   // Put your SqlConnection into using blocks to ensure proper disposal
   using(SqlConnection sqlcon = new SqlConnection(strcon))
   { 
     //  sqlcon.Open();  -- don't open it here already - open as LATE as possible....
     // for SqlDataAdapter - you don't even need to open it yourself - 
     // the data adapter will do this automatically for you
     // and **IF** you open it yourself - you also need to CLOSE it again!

     // *NEVER* use SELECT * in code !! specify the columns you want explicitly
     // string strquery = "select * from testimg";
     string strquery = "SELECT col1, col2, col3 ..... FROM dbo.testimg";  

     SqlDataAdapter da = new SqlDataAdapter(strquery, sqlcon);

     //DataSet ds = new DataSet();  if you only want a single DataTable - no point in having a  whole DataSet ! That's just overhead.....
     //da.Fill(ds);
     //DataTable dt = new DataTable();
     //dt = ds.Tables[0];
     DataTable dt = new DataTable();
     da.Fill(dt);

     // is there a "image" column in your table?? 
     // You need to use the proper column name here!
     byte[] barrImg = (byte[])dt.Rows[7]["image"];
     MemoryStream mstream = new MemoryStream(barrImg);

     pictureBox2.Image = Image.FromStream(mstream);
  }
}

答案 1 :(得分:0)

如果您的错误涉及将图像从数据库转换为流,请尝试修改您的代码::

 byte[] barrImg = (byte[])dt.Rows[7]["image"];

 MemoryStream mstream = new MemoryStream();

 mstream .Write ( barrImg, 0, barrImg.Length );       
 mstream .Seek ( 0, SeekOrigin.Begin );        
 mstream .Close();

 pictureBox2.Image = Image.FromStream(mstream);
相关问题