【发布时间】:2016-03-09 22:50:45
【问题描述】:
我的目标是将图像插入到我的 sql server 数据库中。 数据库中的图像列定义为 varbinary(max) 类型 但是当我执行命令时,Image 列只包含字节数组中的第一个值!
插入图片脚本:
public void InsertImage()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
Image img = Image.FromFile(@"D:\MyProjects\Registry Biometrics Insight\FingerPrintImages\1_2.bmp");
byte[] arr;
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
arr = ms.ToArray();
}
DBLayer dblayer = new DBLayer(CS);
SqlParameter[] sqlParams = new SqlParameter[1];
sqlParams[0] = new SqlParameter("@Image", SqlDbType.VarBinary);
sqlParams[0].Value = arr;
dblayer.M_ExecuteSQLCommand("prc_Fingers_InsertImage", sqlParams);
}
ExecuteSQLCommand 脚本:
public int M_ExecuteSQLCommand(string StoredProcedureName, SqlParameter[] Parameters)
{
SqlCommand comm;
try
{
using (SqlConnection conn = new SqlConnection(_P_ConnectionString))
{
comm = new SqlCommand();
comm.Connection = conn;
comm.CommandType = System.Data.CommandType.StoredProcedure;
comm.CommandText = StoredProcedureName;
comm.CommandTimeout = 0;
comm.Parameters.Clear();
for (int i = 0; i < Parameters.Length; i++)
{
comm.Parameters.Add( Parameters[i] );
}
conn.Open();
comm.ExecuteNonQuery();
return 1;
}
}
catch (Exception ex)
{
throw ex;
}
}
我的排序过程:
Procedure [dbo].[prc_Fingers_InsertImage]
(@Image varbinary = null)
as
begin
INSERT INTO [dbo].[Fingers]
([Image])
VALUES
(@Image)
end
为什么我得到这个结果而不是保存字节数组中的所有值??
【问题讨论】:
-
ms.Rewind() 在写入之后,在转换为数组之前。
-
这是一个很好的例子stackoverflow.com/questions/744589/…
-
ms.Rewind() 在 Visual Studio 2012 中不存在!!! @EricJ。
-
@Mohamad 您现在可能想这样做,但根据我的经验,从长远来看这是不值得的,特别是当您最终遇到存储数千张图像的情况时。数据库随着时间的推移,大小将呈指数级增长,这使得数据库备份和管理变得难以处理。相反,请考虑将图像保存到文件系统,并将图像的路径简单地存储在数据库中。
标签: c# sql sql-server sql-server-2012