Sunday, 1 April 2012

Save & Retrive Images to/from sql server database

In the earlier post I showed how to insert and retrieve simple data from database, In this post what I am going to do is insert images and retrieve them from database. I am going to show this in two main parts:
1. How to save images in the database
2. How to retrieve images back from the database

To save and retrieve images first you should create a table with required fields (Eg. Image Id, Image Name, Image). Lets us now first see how to save images into the database.

Save Images into database

1. Create a form as shown below


2. Code to insert images into database

public partial class Form1 : Form
{
    OpenFileDialog open;
    public Form1()
    {
        InitializeComponent();
    }

    //code for UPLOAD button
    //opens a file dialog for user to choose image to upload
    private void btnUpload_Click(object sender, EventArgs e)
    {
        open = new OpenFileDialog();
        open.InitialDirectory = @"C:\";
        open.Filter = "[JPG,JPEG,GIF,BMP]|*.jpg; *.jpeg; *.gif; *.bmp";
        open.ShowDialog();
    }

    //code for SAVE button
    //convert image to byte array and save it in databse
    private void btnSave_Click(object sender, EventArgs e)
    {
        if (txtImageName.Text == "")
        {
           MessageBox.Show("Enter image Name");
        }
        else
        {
            FileStream fs = new FileStream(@open.FileName, FileMode.Open, FileAccess.Read);
            byte[] image = new byte[fs.Length];
            fs.Read(image, 0, Convert.ToInt32(fs.Length));
            string name = txtImageName.Text;

            //create database connection
            string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();

            //sql statement to insert image into database
            string sql = "INSERT INTO Images (ImageName, Image) VALUES (@ImageName, @Image)";

            //code to insert into database
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@ImageName", name);
            cmd.Parameters.AddWithValue("@Image", image);

            //check if image is added to database
            int result = cmd.ExecuteNonQuery();
            if (result > 0)
                MessageBox.Show("Image Successfully Added!");
            else
                MessageBox.Show("Failed to Add Image!");
        }
            
    }
}
 
Retrieve Images from database

1. Create a form as shown below 


 2. Code for View button 

//create database connection
string connectionString = "Data Source=abc;Initial Catalog=abc;User ID=abc;Password=abc";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

//sql query to retrive data from database
string sql = "SELECT Image FROM Images WHERE ImageName = @ImageName";
SqlCommand cmd = new SqlCommand(sql, connection);
SqlParameter param = new SqlParameter();
param.ParameterName = "@ImageName";
param.Value = comboBox1.SelectedValue;
cmd.Parameters.Add(param);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
    //display the retrieved image
    MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Image"]);
    pictureBox1.Image = Image.FromStream(ms);
    pictureBox1.Refresh();
}
 

No comments:

Post a Comment