简体   繁体   English

如何在图片框中显示来自访问数据库的附件图像

[英]How to Display attachments image from access db in picturebox

im trying to display image from database Attachments in picturebox but im getting error on我试图在图片框中显示来自数据库附件的图像,但我收到错误

ImageByte = (byte[]) vcom.ExecuteScalar();

it say它说

Unable to cast object of type 'System.String' to type 'System.Byte[]'.无法将“System.String”类型的 object 转换为“System.Byte[]”类型。

here is my code这是我的代码

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

In MSAccess , attachments binary data are located in a sub element of the Attachment field.MSAccess中,附件二进制数据位于附件字段的子元素中。

This will return a byte[] .这将返回一个byte[] This byte[] is padded by MSAccess , first 20 bytes are contains MetaData .此 byte[] 由MSAccess填充,前 20 个字节包含MetaData

You can use Linq .Skip() to get rid of those first 20 bytes您可以使用 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;
...

Does this work?这行得通吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM