Importing a bitmap image from an Access database into a C# program

后端 未结 2 1188
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 12:29

I have a C# program in visual studio 2010 where I am accessing the data from my access database. I can get all of the information, except for the image. I have followed the step

相关标签:
2条回答
  • 2021-01-23 12:38

    The procedure you describe in your question for inserting bitmap images into an Access database will save the image imbedded in an OLE Object. If you want to use just the bitmap image in your C# program you need to remove the OLE "wrapper" from the binary data that is retrieved from Access.

    For example, if I retrieve it from the Access database and try to convert it directly to a new Bitmap object...

    private void Form1_Load(object sender, EventArgs e)
    {
        using (var con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Public\Database1.accdb;"))
        {
            con.Open();
            using (var cmd = new OleDbCommand("SELECT LastName, FirstName, Photo FROM Clients WHERE ID=3", con))
            {
                OleDbDataReader rdr = cmd.ExecuteReader();
                rdr.Read();
                this.textBox1.Text = rdr["FirstName"].ToString();
                this.textBox2.Text = rdr["LastName"].ToString();
                byte[] photoBytes = (byte[])rdr["Photo"];
                var ms = new System.IO.MemoryStream(photoBytes);
                this.pictureBox1.Image = new System.Drawing.Bitmap(ms);
                ms.Close();
            }
            con.Close();
        }
    }
    

    ...I get a "Parameter is not valid" error:

    Parameter.png

    However, if I remove the OLE "wrapper" using the GetImageBytesFromOLEField method of the OleImageUnwrap class in my other answer here...

    var ms = new System.IO.MemoryStream(OleImageUnwrap.GetImageBytesFromOLEField(photoBytes));
    

    ...then it works:

    Hank.png

    0 讨论(0)
  • 2021-01-23 12:56

    Memory stream can be created from byte array and Image can be made from memory stream. The following code will compile:

    byte[] bytes = new byte[0];  
    MemoryStream ms = new MemoryStream(bytes);  
    Image img = Image.FromStream(ms);
    
    0 讨论(0)
提交回复
热议问题