关于从Image字段读取图片流并显示在PictureBox控件时报‘参数无效’异常的解决方法...

    问题出在存储图片信息的代码中,SqlParameter构造函数中的[Size]参数不是Image字段的长度(16),而是字节数组的长度。 可用一下两种构造方式构造SqlParameter

    SqlParameter para = new SqlParameter("@ImageCol", SqlDbType.Image, bytes.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, bytes);

  或 SqlParameter para = new SqlParameter("@ImageCol", SqlDbType.Image,bytes.Length);
                para.Value = bytes;

ContractedBlock.gif ExpandedBlockStart.gif Code
try
ExpandedBlockStart.gifContractedBlock.gif            
{
                SqlConnection con 
= new SqlConnection(connString);
                SqlCommand cmd 
= new SqlCommand("insert into TestImage values(@ImageCol)", con);
                String strBLOBFilePath 
= this.open.FileName;//Modify this path as needed.

                
//从一个包含图片的路径中读取图片信息到流 
                FileStream fileStream = new FileStream(this.open.FileName, FileMode.Open, FileAccess.Read);
                Byte[] bytes 
= new Byte[fileStream.Length];
                fileStream.Read(bytes, 
0, bytes.Length);
                fileStream.Close();

                
//添加ImageCol列的参数 
                SqlParameter para = new SqlParameter("@ImageCol", SqlDbType.Image, bytes.Length, ParameterDirection.Input, false,
                            
00null, DataRowVersion.Current, bytes);
                cmd.Parameters.Add(para);

                
//上传图片流信息 
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }

            
catch (Exception ex)
ExpandedBlockStart.gifContractedBlock.gif            
{ MessageBox.Show(ex.Message); }

 

二。读取图片信息

 

ContractedBlock.gif ExpandedBlockStart.gif Code
            try
ExpandedBlockStart.gifContractedBlock.gif            
{
                SqlConnection cn 
= new SqlConnection(connString);
                cn.Open();

                
//从数据库获取图片流信息 
                SqlCommand cmd = new SqlCommand("select ImageCol from TestImage", cn);
                SqlDataAdapter da 
= new SqlDataAdapter(cmd);
                DataTable dt 
= new DataTable();
                da.Fill(dt);


                
//假设只有一条记录
                Byte[] byteImageCol = (Byte[])(dt.Rows[0]["ImageCol"]);
                MemoryStream stmImageCol 
= new MemoryStream(byteImageCol);
                pictureBox1.Image 
= Image.FromStream(stmImageCol);

                cn.Close();
            }

            
catch (Exception ex)
ExpandedBlockStart.gifContractedBlock.gif            
{ MessageBox.Show(ex.Message); }

 

 

转载于:https://www.cnblogs.com/gossip/archive/2009/06/18/1505953.html

你可能感兴趣的:(关于从Image字段读取图片流并显示在PictureBox控件时报‘参数无效’异常的解决方法...)