Load a saved image from an Access database in C#

The post Save an image in an Access database in C# explains how to save an image in an Access database. This post explains how to load that image and display it.

Like previous examples, this program uses a SQL statement of the form "SELECT * FROM Books WHERE..." to select a record from the database. It uses the following code to display the image stored in returned record's field number 6.
Bitmap bm = BytesToImage((byte[])reader.GetValue(6));
picCover.Image = bm;

This code simply fetches the data in field 6, casts it into an array of bytes, and passes it to the BytesToImage method to convert the bytes into a Bitmap. The following code shows the BytesToImage method.

// Convert a byte array into an image.
private Bitmap BytesToImage(byte[] bytes)
{
    using (MemoryStream image_stream = new MemoryStream(bytes))
    {
        Bitmap bm = new Bitmap(image_stream);
        image_stream.Close();
        return bm;
    }
}

This method creates a MemoryStream associated with the byte array. It creates a new Bitmap passing its constructor the MemoryStream, and returns the Bitmap.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.