【问题标题】:save image to sql server 2012 using c#使用 c# 将图像保存到 sql server 2012
【发布时间】: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


【解决方案1】:

您可能希望使用“读取”方法将流转换为字节数组

ms.Read(arr, 0, ms.Length);

我什至会在之前声明“arr”字节数组的大小,您将流读入数组

arr = new byte[ms.length];

您可能还需要重置流指针,因为在 Save 方法之后,指针位于流的末尾:

ms.Seek(0, SeekOrigin.Begin);

最终的代码块会导致替换

arr = ms.ToArray();

ms.Seek(0, SeekOrigin.Begin);
arr = new byte[ms.length];
ms.Read(arr, 0, ms.Length);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2013-06-26
    • 2014-07-06
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多