How to Save and Retrieve Image from SQL database in C#

By FoxLearn 11/21/2024 2:24:58 PM   19.64K
To save and retrieve images from an SQL database using Entity Framework in C#, you need to follow a few steps to handle binary data properly, such as saving images as byte arrays (byte[]) in the database and retrieving them correctly.

Open Visual Studio, then click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "SaveImageToDatabase" and then click OK

Drag and drop PictureBox, Button, Label, ListView controls from the Visual Toolbox onto your form designer, then design your form as shown below.

save image to sql database in c#

How to handle saving and loading images from a SQL database using Entity Framework in a Windows Forms application.

Create a MyPicture table, then add to EF Model as shown below.

entity framework model

Ensure that your MyPicture model and PicEntities context are set up as follows

public class MyPicture
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public byte[] Data { get; set; }  // To store the image as a byte array
}

public class PicEntities : DbContext
{
    public DbSet<MyPicture> MyPictures { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Make sure to replace with your actual connection string
        optionsBuilder.UseSqlServer("connectionString");
    }
}

You already implemented this method correctly to convert the byte array back into an image and display it in the pictureBox.

// c# convert binary to image
Image ConvertBinaryToImage(byte[] data)
{
    using (MemoryStream ms = new MemoryStream(data))
    {
        return Image.FromStream(ms);
    }
}

Converts the image from the pictureBox into a byte array that can be stored in the database.

// c# convert image to binary
byte[] ConvertImageToBinary(Image img)
{
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        return ms.ToArray();
    }
}

Add a btnSave_Click event handler to the Save button, This method takes the image from the pictureBox, converts it into a byte array, and stores it in the database asynchronously using Entity Framework.

private async void btnSave_Click(object sender, EventArgs e)
{
    // Save image to SQL database using Entity Framework (async)
    using (PicEntities db = new PicEntities())
    {
        MyPicture pic = new MyPicture() { FileName = fileName, Data = ConvertImageToBinary(pictureBox.Image) };
        db.MyPictures.Add(pic);
        await db.SaveChangesAsync();
        MessageBox.Show("You have been successfully saved.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

The image is saved to the database as an image object, which includes a file name and the image data in binary format.

Add a btnLoad_Click event handler to the Load button, When you click the load button, all the images are loaded from the database into the ListView control. The ListView will show the image filenames.

private void btnLoad_Click(object sender, EventArgs e)
{
    listView.Items.Clear();
    // Load image from sql database to listview
    using (PicEntities db = new PicEntities())
    {
        list = db.MyPictures.ToList();
        foreach (MyPicture pic in list)
        {
            ListViewItem item = new ListViewItem(pic.FileName);
            listView.Items.Add(item);
        }
    }
}

The images are loaded from the database into a ListView, allowing the user to select an image, which will then be displayed in the pictureBox.

When an image is selected from the ListView, the corresponding image data is displayed in the pictureBox.

For example, Selecting and Displaying Image (listView_SelectedIndexChanged)

private void listView_SelectedIndexChanged(object sender, EventArgs e)
{
    if (listView.FocusedItem != null)
    {
        // Set image to picture box
        pictureBox.Image = ConvertBinaryToImage(list[listView.FocusedItem.Index].Data);
        lblFilename.Text = listView.FocusedItem.SubItems[0].Text;
    }
}

The user selects an image file, which is displayed in the pictureBox.

For example, File Selection (btnOpen_Click)

private void btnOpen_Click(object sender, EventArgs e)
{
    //Read image file
    using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "JPEG|*.jpg", ValidateNames = true, Multiselect = false })
    {
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            fileName = ofd.FileName;
            lblFilename.Text = fileName;
            pictureBox.Image = Image.FromFile(fileName);
        }
    }
}

Add code to handle your form as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SaveImageToDatabase
{
    public partial class Form1 : Form
    {
        string fileName;
        List<MyPicture> list;

        public Form1()
        {
            InitializeComponent();
        }
    }
}

This example allows you to interact with a SQL database using Entity Framework to save and retrieve images in a Windows Forms application.

VIDEO TUTORIAL