无法将byte []转换为图像

时间:2015-08-29 13:00:13

标签: c# sql-server

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

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作为参数无效。我在互联网上尝试了所有可用的解决方案,但都是徒劳的。

2 个答案:

答案 0 :(得分:0)

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

byte[] image = reader.GetFieldValue<byte[]>(0);

如果您不使用.NET 4.5,您可以直接询问该字段并手动投射。

byte[] image = (byte[])reader.GetValue(0);

但是,如果您只使用第一行中的第一列,则根本不需要DataReader,只需使用ExecuteScalar()即可。 (我也正在清理您的代码以使用正确的using语句并将您的ex.Message切换为ex.ToString()以在错误对话框中提供更多信息。)

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

答案 1 :(得分:-1)

试试这个:

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);
}
相关问题