C# Exercises

Home AgriMetSoft About Contact

Save Image to SQL in C# | Retrieve Image from SQL Table

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

namespace save_image_to_sql_server
{
  public partial class Form1 : Form
  {
    string connetionString = @"Data Source=DESKTOP-J9K51EL\AMSSQL;Initial Catalog=Database1;Integrated Security=True";
    public Form1()
    {
      InitializeComponent();
    }

    private void select_Image_Click(object sender, EventArgs e)
    {
      OpenFileDialog opf = new OpenFileDialog();

      if (opf.ShowDialog() == DialogResult.OK)
      {
        Image img = Image.FromFile(opf.FileName);
        MemoryStream tmpStream = new MemoryStream();
        img.Save(tmpStream, System.Drawing.Imaging.ImageFormat.Png); // change to other format
        tmpStream.Seek(0, SeekOrigin.Begin);
        byte[] imageData = new byte[img.Size.Height * img.Height];
        tmpStream.Read(imageData, 0, img.Size.Height * img.Height);
        SqlConnection CN = new SqlConnection(connetionString);
        string qry = "INSERT INTO img(Path, logo) VALUES (@p, @image)";

        //Initialize SqlCommand object for insert.
        SqlCommand SqlCom = new SqlCommand(qry, CN);

        //We are passing Original Image Path and
        //Image byte data as SQL parameters.
        SqlCom.Parameters.Add(new SqlParameter("@p", opf.FileName));
        SqlCom.Parameters.Add(new SqlParameter("@image", (object)imageData));

        //Open connection and execute insert query.
        CN.Open();
        SqlCom.ExecuteNonQuery();
        CN.Close();
        MessageBox.Show("The image is stored!");
      }
    }

    private void load_database_Click(object sender, EventArgs e)
    {
      SqlConnection CN = new SqlConnection(connetionString);

      //Initialize SQL adapter.
      SqlDataAdapter ADAP = new SqlDataAdapter("Select * from img", CN);

      //Initialize Dataset.
      DataSet DS = new DataSet();

      //Fill dataset with ImagesStore table.
      ADAP.Fill(DS, "img");
      DataRow Row;
      Row = DS.Tables["img"].Rows[0];
      byte[] MyImg = (byte[])Row[1];
      label1.Text = (string)Row[0];
      MemoryStream ms = new MemoryStream(MyImg);
      ms.Position = 0;
      Image img = Image.FromStream(ms);
      pictureBox1.Image = img;
      CN.Close();
    }
  }
}

		
	 


Download the project of Visual Studio 2013 in DropBox Download


How to Save an Image to SQL Server Database in C# and Retrieve Image to a Pricturebox


List of Exercises