使用c#将数据库访问中的长二进制数据转换为图像

时间:2017-01-26 16:28:58

标签: c# ms-access

这是我的代码:

try
{
    connection.Open();
    OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
    string query = "select * from StudentInformation where [StudentID] = " + txtStudentID.Text + "";
    command.CommandText = query;
    OleDbDataReader read = command.ExecuteReader();

    while (read.Read())
    {
       txtStudentID.Text = (read["StudentID"].ToString());
       txtFirstname.Text = (read["Firstname"].ToString());
       txtLastname.Text = (read["Lastname"].ToString());

        byte[] imgbyte = (byte[])read["Image"];    //when i add this a got error with this code
        MemoryStream ms = new MemoryStream(imgbyte);
        StudentPicture.Image = Image.FromStream(ms);
    }

    connection.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

我收到错误“参数无效” 有人可以帮帮我吗? 我很困惑! 我尝试了所有搜索但仍然错误的代码:'( 对不起,我的英语不好 非常感谢您的回复......

1 个答案:

答案 0 :(得分:0)

尝试获取这样的字节数组:

var binLength = read.Item[3].Length;
byte[] imgByte = new byte[binLength - 1];
var bytes = read.GetBytes(0,0,imgByte,0,imgByte.Length);
MemoryStream ms = new MemoryStream(imgByte);
StudentPicture.Image = Image.FromStream(ms);