如何通过.NET将图像插入Access OLE字段
我有一个Access .mdb数据库,我想从visual C#2010开发的应用程序中插入一个图像。图片存储在OLE-object字段的数据库中。
在Access中直接添加图像后,它们以位图图像的格式存储。 只需双击即可在Access中打开这些图片。
我有以下代码:
OdbcConnection Connection = new OdbcConnection(); ... sql = "INSERT INTO film (poster) VALUES (" ' " + Image.FromFile(textBox8.Text) + " ' ");"; //texbox are stored the picture name OdbcCommand Command = new OdbcCommand(sql, Connection); Command.ExecuteNonQuery();
代码运行良好,但Access将图片存储为二进制数据,并且无法在Access中再次打开。 请告诉我如何将图像作为位图图像插入。 谢谢。
这是一个有点不同寻常的要求。 大多数人在Access中询问OLE嵌入图像是在询问如何将它们从 OLE对象转换为原始二进制数据,而不是相反。 当前版本的Access具有像Image
控件这样的function,可以显示位图图像,而无需处理添加到对象数据中的OLE“包装器”的复杂性。
不过,这里有一种方法可以满足您的要求。 它使用Access.Application
对象,因此必须在计算机上安装Access才能使其正常工作。 它还需要Access数据库中的Form
- 表单本身绑定到包含要插入的OLE图像字段的表,
- 窗体上唯一的控件是
Bound Object Frame
,绑定到OLE字段。
示例代码还假定正在更新的表具有名为[ID]的数字主键字段。
private void button1_Click(object sender, EventArgs e) { // test data int recordIdToUpdate = 15; string bmpPath = @"C:\Users\Gord\Pictures\bmpMe.bmp"; var paths = new System.Collections.Specialized.StringCollection(); paths.Add(bmpPath); Clipboard.SetFileDropList(paths); // COM Reference required: // Microsoft Access 14.0 Object Library var accApp = new Microsoft.Office.Interop.Access.Application(); accApp.OpenCurrentDatabase(@"C:\Users\Public\Database1.accdb"); accApp.DoCmd.OpenForm( "PhotoForm", Microsoft.Office.Interop.Access.AcFormView.acNormal, null, "ID=" + recordIdToUpdate); accApp.DoCmd.RunCommand(Microsoft.Office.Interop.Access.AcCommand.acCmdPaste); accApp.DoCmd.Close( Microsoft.Office.Interop.Access.AcObjectType.acForm, "PhotoForm", Microsoft.Office.Interop.Access.AcCloseSave.acSaveNo); accApp.CloseCurrentDatabase(); accApp.Quit(); this.Close(); }
private string ImageToBase64String(Image image) { using (MemoryStream stream = new MemoryStream()) { image.Save(stream, image.RawFormat); return Convert.ToBase64String(stream.ToArray()); } } private void SaveButton() { string Pic = ImageToBase64String(PicBox.Image); OleDbCommand PicSave = new OleDbCommand("INSERT INTO Picture(ID,PICTURE)VALUES(" + PicId.Text + ",'" + Pic + "')", con); con.Open(); var SaveValue = PicSave.ExecuteNonQuery(); if (SaveValue > 0) { MessageBox.Show("Record Saved", "Information"); ValueClear(); } else MessageBox.Show("Rocord Not Saved", "Erro Msg"); con.Close(); }