Save images in an Access database in WPF and C#

[save images]

The example Display images in an Access database in WPF and C# shows how you can display images saved in an Access database. Of course that begs the question, “How do you save images in the database in the first place?” This example shows one way to do that.

When you select a book from the ListBox and then click the Set Image button, the following code executes.

// Set the image for this title.
private void btnSetImage_Click(object sender, RoutedEventArgs e)
    OpenFileDialog dlg = new OpenFileDialog();
    dlg.Filter =
        "Image files|*.bmp;*.jpg;*.gif;*.png;*.tif|All files|*.*";
    dlg.FilterIndex = 1;

    if (dlg.ShowDialog() == true)
            // Display the image.
            BitmapImage bm =
                new BitmapImage(new Uri(dlg.FileName));
            imgCover.Source = bm;

            // Set the image in the database.
            // The CoverImage field has type OLE Object.
            string title =
                lstTitles.SelectedItem.ToString().Replace("'", "''");
            OleDbCommand cmd = new OleDbCommand(
                "UPDATE Books SET CoverImage=@Image WHERE Title='" +
                title + "'",

            // Create a byte array holding the image.
            byte[] image_bytes = ImageToBytes(bm);

            // Add the image as a parameter.
            OleDbParameter param = new OleDbParameter();
            param.OleDbType = OleDbType.Binary;
            param.ParameterName = "Image";
            param.Value = image_bytes;

            // Execute the command (with no return value).
            cmd.Connection = Conn;
        catch (Exception ex)
            if (Conn.State != ConnectionState.Closed)

This code starts by creating an OpenFileDialog, setting its Filter and FilterIndex properties, and displaying the dialog. If the user selects a file, the method creates a BitmapImage from the file and displays it in the imgCover Image control.

Next the code creates a SQL INSERT statement to update the selected title’s image. It calls the ImageToBytes method (described shortly) to convert the BitmapImage into an array of bytes and creates a parameter object for the bytes. It then calls the command’s ExecuteScalar method to update the record.

The following code shows the ImageToBytes method.

// Convert a BitmapImage into a byte array.
private static byte[] ImageToBytes(BitmapImage image)
    byte[] data;
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    using (MemoryStream ms = new MemoryStream())
        data = ms.ToArray();
    return data;

This method creates a JpegBitmapEncoder object to encode a bitmap as JPEG data. It adds a frame to the encoder to represent the image. It then creates a MemoryStream and calls the encoder’s Save method to make it write its data into the MemoryStream. Finally the code calls the MemoryStream‘s ToArray method to convert the data into a byte array, which the method returns.

Download the example to see additional details such as how the Load All button loads all of the records’ pictures at once and how the Remove All button removes all of the books’ pictures.

Download Example   Follow me on Twitter   RSS feed   Donate

About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in database, graphics, image processing, Office and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.