问题出在存储图片信息的代码中,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;
Code
try
{
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,
0, 0, null, DataRowVersion.Current, bytes);
cmd.Parameters.Add(para);
//上传图片流信息
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
try
{
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,
0, 0, null, DataRowVersion.Current, bytes);
cmd.Parameters.Add(para);
//上传图片流信息
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }
二。读取图片信息
Code
try
{
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)
{ MessageBox.Show(ex.Message); }
try
{
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)
{ MessageBox.Show(ex.Message); }