简体   繁体   English

从SQL Server检索图像

[英]Retrieving an image from SQL Server

I wrote this code but faced an exception that said: Parameter Not Valid. 我编写了这段代码,但是遇到了一个异常: 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();

The exception is: 例外是:

Parameter is not valid.

in the Image.FromStream line of code. Image.FromStream代码行中。

I checked the value that in datatable was assigned to the image field. 我检查了datatable中分配给image字段的值。 It was System.Byte[] . 那是System.Byte[] I traced the code. 我跟踪了代码。 Every thing seems to be correct. 每件事似乎都是正确的。 But it does not work. 但这行不通。

I searched around this problem. 我搜索了这个问题。 Another site preferred to set mstream.Position = 0 . 最好将另一个站点设置为mstream.Position = 0 But that does not work. 但这不起作用。

I stored my image by this code.If it maybe that I saved this wrong! 我用这个代码存储了我的图像,如果可能我保存错了!

    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();

new code to save the image: 保存图像的新代码:

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;
}

and : 和:

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();
}

Um, that's not going to work. 嗯,那行不通。

Your code that "stores" the image, well, doesn't really do what you think it does. 您的“存储”图像的代码实际上并没有真正实现您认为的功能。

It is putting the value "test.jpg" into the image field. 它将 “ test.jpg”放入图像字段。 That isn't the binary image data; 那不是二进制图像数据。 only the filename . 文件名

So, when you go to pull it back out the Image.FromStream(mstream) call is going to blow chunks because the value "test.jpg" is not an image.. ergo: the parameter is not valid 因此,当您将其撤回时,由于值“ test.jpg”不是图像,因此Image.FromStream(mstream)调用将删除数据块。ergo:该参数无效

Here is an example of what you need to be doing to actually put the image into the database: 这是实际将图像放入数据库中需要执行的操作示例:

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

You close the stream then try to pull an image from the stream, hence the error "cannot access a closed stream." 您关闭流,然后尝试从流中提取图像,因此错误“无法访问关闭的流”。

Try swapping the order of your last two lines: 尝试交换最后两行的顺序:

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

Would simplify things. 会简化事情。 I suspect your problem would be you need to call mStream.Flush() after write and before the seek. 我怀疑您的问题是您需要在写入之后和查找之前调用mStream.Flush()。

To put an image in to a database, one way is. 将图像放入数据库的一种方法是。

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();
  }
}

Notice it puts the content of teh file in the database. 注意,它将teh文件的内容放入数据库中。 Since in the case of a jpg that content is most definitely not a string, use a parameterised query. 由于对于jpg而言,内容绝对不是字符串,因此请使用参数化查询。 Which youi should be doing anyway, develop a good habit. 无论如何,您应该养成一个好习惯。 You also need to suss out using, your code was leaking resources all over the place. 您还需要暂停使用,因为您的代码正在各处泄漏资源。

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

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