Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

c# - Retrieve an image from access database

Please can anyone help me in this code ??

I am trying to retrieve an image from an Access database..

private void btnRetrieve_Click_1(object sender, EventArgs e)
{
   //Save Temporarily that image bytes in one location and give that path to picture box 
   con.Open();

   cmd = new OleDbCommand("select pic from shapes2 where ID= 1", con);

   da = new OleDbDataAdapter(cmd);
   da.Fill(dt);

   if (dt.Rows.Count > 0)
   {
      if (dt.Rows[0]["pic"] != DBNull.Value)
      {
         pictureBox4.Image = ByteArrayToImage((Byte[])dt.Rows[0]["pic"]);
      }
   }

   con.Close();
}

Bitmap ByteArrayToImage(byte[] b)
{
    MemoryStream ms = new MemoryStream();
    byte[] pData = b;
    ms.Write(pData, 0, Convert.ToInt32(pData.Length));
    Bitmap bm = new Bitmap(ms, false);
    ms.Dispose();
    return bm;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This seems to be a common issue, see the discussion: Reading image from Access - parameter not valid

The issue is that images can be stored in Access databases in different formats: binary blob or as an OLE object.

I do not know which one you are using in your Access database, but if it's save as a straight binary blob then it is the image itself, so your code should work.

Since you are having the issue, it probably means that the images were stored differently: as OLE object. In that case there is metadata also stored with the image data and that metadata makes getting to the image more difficult since you have to strip it away one way or another. The OLE metadata is of variable length, so you can't just skip it.
The best way I have seen it done is to find the begining of the image file by trying to find its' magic number in the OLE blob.

The following articles and question will show you how:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...