C# 无法将字节[]转换为图像

C# 无法将字节[]转换为图像,c#,sql-server,C#,Sql Server,我正在尝试检索存储在MS SQL Server数据库中的图片。列的类型为image。我的代码是: try { SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString); SqlCommand cmd = new SqlCommand(string.Empty, con); cmd.CommandText = "select Picture from Person"

我正在尝试检索存储在MS SQL Server数据库中的图片。列的类型为image。我的代码是:

try
{
    SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
    SqlCommand cmd = new SqlCommand(string.Empty, con);
    cmd.CommandText = "select Picture from Person";
    con.Open();
    SqlDataReader dataReader = cmd.ExecuteReader();
    dataReader.Read();

    byte[] image = new byte[10000];
    long len = dataReader.GetBytes(0, 0, image, 0, 10000);

    using (MemoryStream stream = new MemoryStream(image))
    {
        stream.Seek(0, SeekOrigin.Begin);
        pictureBox1.Image = Image.FromStream(stream);
    }
    con.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}
当我设置pictureBox1.Image属性时,由于参数无效,我不断获取
ArgumentException
。我在互联网上尝试了所有可用的解决方案,但都没有成功。

试试这个:

SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream mStream = new MemoryStream(image))
{
    pictureBox1.Image = Image.FromStream(mStream);
}

您始终使用
10000
字节数组,即使图像更小(或更大)。不要手动创建
byte[]
,如果您需要,
DataReader
可以提供整个字节数组

byte[] image = reader.GetFieldValue<byte[]>(0);
但是,如果您只使用第一行的第一列,则根本不需要
DataReader
,只需使用
ExecuteScalar()
。(我还在清理您的代码,以便使用适当的
语句,并将
ex.Message
切换到
ex.ToString()
,以便在错误对话框中提供更多信息)


除了删除
stream.Seek(0,SeekOrigin.Begin)之外,可能存在重复我看不到对代码的任何更改(顺便说一句,这根本不会更改程序,流已经位于位置0,因此搜索实际上根本没有移动它)。同样,这仍然不能解决问题,您不尝试读取大于
10000的图像,而是向
MemoryStream
发送可能额外的未初始化字节
byte[] image = (byte[])reader.GetValue(0);
try
{
    using(SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
    using(SqlCommand cmd = new SqlCommand(string.Empty, con))
    {
        cmd.CommandText = "select Picture from Person";
        con.Open();

        byte[] image = (byte[])cmd.ExecuteScalar();

        using (MemoryStream stream = new MemoryStream(image))
        {
            pictureBox1.Image = Image.FromStream(stream);
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}