将Access数据库中的位图图像导入C#程序

我在visual studio 2010中有一个C#程序,我从访问数据库访问数据。 除了图像,我可以获得所有信息。 我已按照此处的步骤将图片嵌入到访问数据库中。

Right-click the first field in the Image column of the table and click Insert Object. Click Create from File, and then click Browse. Browse to one or more Windows Bitmap (.bmp) or Device Independent Bitmap (.dib) images. You can find a set of BMP files, named Empid1.bmp through Empid9.bmp, at drive:\Program Files\Microsoft Office\OFFICE11\SAMPLES. Select the first image and click OK. 

我使用了位图图像的位置。 我有一个包含位图属性的构造函数,但是当它试图去表获取所有信息时,我得到错误:“无法将System.Byte []的对象强制转换为System.Drawing.Bitmap。” 不知道为什么它说图像存储为系统字节。

找到了这个post。 所以我尝试了内存流,但同样的问题,无法将系统字节转换为system.io.memorystream。

您在问题中描述的用于将位图图像插入Access数据库的过程将保存嵌入在OLE对象中的图像。 如果只想在C#程序中使用位图图像,则需要从Access中检索的二进制数据中删除OLE“包装器”。

例如,如果我从Access数据库中检索它并尝试将其直接转换为新的Bitmap对象…

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

…我收到“参数无效”错误:

Parameter.png

但是,如果我在这里的其他答案中使用OleImageUnwrap类的OleImageUnwrap方法删除OLE“包装器”…

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

…然后它的工作原理:

Hank.png

可以从字节数组创建内存流,也可以从内存流中创建Image。 以下代码将编译:

 byte[] bytes = new byte[0]; MemoryStream ms = new MemoryStream(bytes); Image img = Image.FromStream(ms);