Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Loading an Image and Saving it into a database

0.00/5 (No votes)
23 Aug 2011 1  
How to load an image from the filesystem and save it into a Database
As part of a project I required to load an image, display it in a picture box and save it into a database. Quite simple really ( at least in theory ).

The whole process can be summarized in the following steps:
1.Load the image file into a picture box
C#
private void btnBadLoad_Click(object sender, EventArgs e) {
  OpenFileDialog dlg = new OpenFileDialog();
  DialogResult dr = dlg.ShowDialog();
  if (dr == DialogResult.OK) {
    pbPicture.Load(dlg.FileName);
  }
}

2.Convert the image from the picture box into an array of bytes using a stream.
C#
private byte[] ImageToByteArray(Image img,ImageFormat format) {
  byte[] result;
  try {
    MemoryStream ms = new MemoryStream();
    img.Save(ms , format);
    result = ms.ToArray();
  } catch (Exception ex) {
    Console.Write(ex.StackTrace);
    throw;
  }
  return result;
}

3.Create an insert command and pass the byte array as a parameter
C#
DbCommand cmd =  _dbu.CreateTextCommand(insQ);
cmd.AddParameter("@ImageId", id);
cmd.AddParameter("@ImageData", imageBytes);
cmd.ExecuteNonQuery();

During step 2 a rather obnoxious "Generic GDI+ Exception" appeared without apparent reason.After some research I found this is a designed behavior, as described in the following article.
http://support.microsoft.com/?id=814675
Apparently when an image is created from a file it gets locked allong with the file and no further streaming is possible.

The solution to this quandary is to change the way the image is loaded in step 1, disposing of the file-locked bitmap as fast as possible.
C#
private void btnLoad_Click(object sender, EventArgs e) {
  OpenFileDialog dlg = new OpenFileDialog();
  DialogResult dr = dlg.ShowDialog();
  if (dr == DialogResult.OK) {
    //Create the file-locked bitmap
    Bitmap b1 = new Bitmap(dlg.FileName);
    //Copy it into the picture image
    pbPicture.Image = (Bitmap)b1.Clone();
    //Say "Hasta la vista baby" to the file-locked bitmap
    b1.Dispose();
  }
}

Happy image saving !!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here