Save several images into Access in C#

[save several images]

The example Save images in an Access database in C# includes an Access database. Unfortunately if you save several images into the database and then open the database in Access, Access removes the images. It just doesn’t seem to understand image data.

To make using the database easier, the example program includes a Load All button that loads several images at once. It loads one picture for each of the records in the Books table. The program uses the following code to load those images.

// Load images for all of the records.
private void btnLoadAll_Click(object sender, EventArgs e)
{
    string[] titles =
    {
        "Advanced Visual Basic Techniques",
        "Beginning Database Design Solutions",
        ...
    };
    string[] filenames =
    {
        @"Images\avbts.jpg",
        @"Images\db_design_s.jpg",
        ...
    };

    this.Cursor = Cursors.WaitCursor;

    string image_dir = Path.GetFullPath(
        Path.Combine(Application.StartupPath, "..\\..")) + "\\";
    
    // Load the images.
    for (int i = 0; i < titles.Length; i++)
    {
        LoadRecordImage(titles[i], image_dir + filenames[i]);
    }

    this.Cursor = Cursors.Default;
    MessageBox.Show("Loaded " + titles.Length + " images.");
}

The method starts by creating two arrays, one holding the titles of books and the other holding the names of image files. The images are stored in the project’s Images subdirectory so the file names start with Images\.

After defining the arrays, the program uses the Path class’s Combine method to combine the application’s startup path with the relative path ..\.. to find the project directory. (The one containing the code, not the executable.) It then uses GetFullPath to turn the combined path into a valid fully-qualified path.

The code loops through the book titles, calling the LoadRecordImage method shown in the following code for each title and file name.

// Load one record's picture.
private void LoadRecordImage(string title, string filename)
{
    try
    {
        // Get the image.
        Bitmap bm = new Bitmap(filename);

        // Set the image in the database.
        title = title.Replace("'", "''");
        OleDbCommand cmd = new OleDbCommand(
            "UPDATE Books SET CoverImage=@Image WHERE Title='" +
            title + "'",
            Conn);

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

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

        // Execute the command (with no return value).
        cmd.Connection = Conn;
        Conn.Open();
        cmd.ExecuteScalar();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        Conn.Close();
    }
}

The LoadRecordImage method loads a bitmap. It then creates a SQL UPDATE statement to save the bitmap in the Books record for the given title.

To do that, it creates an OleDbParameter object for the bitmap, defines its properties appropriately, and executes the UPDATE statement.

Note that inserting images into the database isn’t super fast so adding even the 17 images in this example takes a couple seconds.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in database, graphics, image processing, Office and tagged , , , , , , , , , , , , , , , , , , . Bookmark the permalink.

One Response to Save several images into Access in C#

  1. asava samuel says:

    Here is a database compatible with .NET, Silverlight, Windows Phone, Mono, Monodroid, and Monotouch:
    http://www.kellermansoftware.com/p-43-ninja-net-database-pro.aspx

Leave a Reply

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