繁体   English   中英

从SQL Server检索图像

[英]Retrieving an image from SQL Server

我编写了这段代码,但是遇到了一个异常: Parameter Not Valid.

    string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = connstr;

    conn.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;

    cmd.CommandText = "SELECT * FROM tbl";

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;

    DataTable dt = new DataTable();
    da.Fill(dt);

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

    MemoryStream mstream = new MemoryStream();

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

    img.Image = Image.FromStream(mstream);
    mstream.Close();

例外是:

Parameter is not valid.

Image.FromStream代码行中。

我检查了datatable中分配给image字段的值。 那是System.Byte[] 我跟踪了代码。 每件事似乎都是正确的。 但这行不通。

我搜索了这个问题。 最好将另一个站点设置为mstream.Position = 0 但这不起作用。

我用这个代码存储了我的图像,如果可能我保存错了!

    string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = connstr;

    conn.Open();

    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;

    string sql = "INSERT INTO tbl (name, family, image) VALUES ('name', 'family', '{0}')";
    sql = string.Format(sql, Image.FromFile("test.jpg"));

    cmd.CommandText = sql;
    cmd.ExecuteNonQuery();
    conn.Close();

保存图像的新代码:

public byte[] ReadFile(string sPath)
{
    byte[] data = null;


    FileInfo fInfo = new FileInfo(sPath);
    long numBytes = fInfo.Length;

    FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

    BinaryReader br = new BinaryReader(fStream);

    data = br.ReadBytes((int)numBytes);

    return data;
}

和:

private void cmdSave_Click(object sender, EventArgs e)
{
    string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

      byte[] imageData = ReadFile("test.jpg");

      SqlConnection CN = new SqlConnection(connstr);

      string qry = "insert into tbl (name, family, image) VALUES ('name', 'family', '{0}')";
      qry = string.Format(qry, imageData);

      SqlCommand SqlCom = new SqlCommand(qry, CN);

      CN.Open();
      SqlCom.ExecuteNonQuery();
      CN.Close();
}

嗯,那行不通。

您的“存储”图像的代码实际上并没有真正实现您认为的功能。

它将 “ test.jpg”放入图像字段。 那不是二进制图像数据。 文件名

因此,当您将其撤回时,由于值“ test.jpg”不是图像,因此Image.FromStream(mstream)调用将删除数据块。ergo:该参数无效

这是实际将图像放入数据库中需要执行的操作示例:

http://www.codeproject.com/Articles/21208/Store-or-Save-images-in-SQL-Server

您关闭流,然后尝试从流中提取图像,因此错误“无法访问关闭的流”。

尝试交换最后两行的顺序:

img.Image = Image.FromStream(mstream);
mstream.Close();
using (MemoryStream mstream = new MemoryStream((byte[])dt.Rows[1]["image"]))
{
    img.Image = Image.FromStream(mstream);
}

会简化事情。 我怀疑您的问题是您需要在写入之后和查找之前调用mStream.Flush()。

将图像放入数据库的一种方法是。

string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";

using(SqlConnection conn = new SqlConnection(connstr))
{
  using (SqlCommand comm = new SqlCommand(conn))
  {
    comm.CommandText = "INSERT INTO tbl (name, family, image) VALUES (@name,@family,@Content)";
    comm.Parameters.Add(new SqlParameter("name",DbType.String,"Fred"));
    comm.Parameters.Add(new SqlParameter("family",DbType.String,"Flintstone"));
    using(FileStream fs = new FileStream("FredWilmaBamBamAndDino.jpg",FileMode.Open,FileAccess.Read))
    {
      comm.Parameters.Add(new SqlParameter("content",DbType.Image,fs));
    }
    cmd.ExecuteNonQuery();
  }
}

注意,它将teh文件的内容放入数据库中。 由于对于jpg而言,内容绝对不是字符串,因此请使用参数化查询。 无论如何,您应该养成一个好习惯。 您还需要暂停使用,因为您的代码正在各处泄漏资源。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM