如何在图片框中显示来自访问数据库的附件图像
How to Display attachments image from access db in picturebox
我正在尝试在图片框中显示来自数据库附件的图像,但在
上出现错误
ImageByte = (byte[]) vcom.ExecuteScalar();
它说
Unable to cast object of type 'System.String' to type 'System.Byte[]'.
这是我的代码
byte[] ImageByte = null;
MemoryStream MemStream = null;
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/ALL/Database7.accdb";
cn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = cn;
string sql = "select Attachments from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);
ImageByte = (byte[]) vcom.ExecuteScalar();
MemStream = new MemoryStream(ImageByte);
pictureBox1.Image = Image.FromStream(MemStream);
cn.Close();
在 MSAccess
中,附件二进制数据位于附件字段的子元素中。
这将 return 一个 byte[]
。这个 byte[] 由 MSAccess
填充,前 20 个字节包含 MetaData
。
您可以使用 Linq .Skip()
删除前 20 个字节
string sql = "select Attachments.FileData from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);
byte[] ImageByte = (byte[]) vcom.ExecuteScalar(); //contains 20 extra bytes
MemoryStream MemStream = new MemoryStream(ImageByte.Skip(20).ToArray()); //Read bytes starting at position 20
Image image = Image.FromStream(MemStream); //Will work now
pictureBox1.Image = image;
...
这个有用吗?
我正在尝试在图片框中显示来自数据库附件的图像,但在
上出现错误ImageByte = (byte[]) vcom.ExecuteScalar();
它说
Unable to cast object of type 'System.String' to type 'System.Byte[]'.
这是我的代码
byte[] ImageByte = null;
MemoryStream MemStream = null;
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/ALL/Database7.accdb";
cn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = cn;
string sql = "select Attachments from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);
ImageByte = (byte[]) vcom.ExecuteScalar();
MemStream = new MemoryStream(ImageByte);
pictureBox1.Image = Image.FromStream(MemStream);
cn.Close();
在 MSAccess
中,附件二进制数据位于附件字段的子元素中。
这将 return 一个 byte[]
。这个 byte[] 由 MSAccess
填充,前 20 个字节包含 MetaData
。
您可以使用 Linq .Skip()
删除前 20 个字节
string sql = "select Attachments.FileData from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);
byte[] ImageByte = (byte[]) vcom.ExecuteScalar(); //contains 20 extra bytes
MemoryStream MemStream = new MemoryStream(ImageByte.Skip(20).ToArray()); //Read bytes starting at position 20
Image image = Image.FromStream(MemStream); //Will work now
pictureBox1.Image = image;
...
这个有用吗?