Storing and reterview images form database


Sample program developed in C# Windows Application.Which is allow to store image to database and allow you to download the image from database.



Here i Explained a sample program to store the image into database and download the image from database with option of preview of image before save and download.




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

namespace StoreAndDownloadImagesFromSQLServer
{
public partial class frmImagesStore : Form
{
int i;
public frmImagesStore()
{

InitializeComponent();
}

//Get image table rows from sql server to be displayed in Datagrid.
void GetImagesFromDatabase()
{
try
{
//Initialize SQL Server connection.
SqlConnection CN = new SqlConnection(txtConnectionString.Text);

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

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

//Fill dataset with ImagesStore table.
ADAP.Fill(DS, "ImagesStore");

//Fill Grid with dataset.
dataGridView1.DataSource = DS.Tables["ImagesStore"];
button1.Visible = true;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//Connect with SQlDB
private void cmdConnect_Click(object sender, EventArgs e)
{
//Fill datagrid with table rows.
GetImagesFromDatabase();

}

//Open form to get new image file.
private void cmdStoreNewImage_Click(object sender, EventArgs e)
{
frmNewImage fNew = new frmNewImage();
//Supply connection string from this form to frmNewImage form.
fNew.txtConnectionString.Text = txtConnectionString.Text;
fNew.ShowDialog();

//Refresh Image
cmdConnect_Click(null, null);
}

//When user changes row selection, display image of selected row in picture box.
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
try
{
//Get image data from gridview column.
byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["ImageData"].Value;
i = e.RowIndex;
//Initialize image variable
Image newImage;
//Read image data into a memory stream
using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
{
ms.Write(imageData, 0, imageData.Length);

//Set image variable value using memory stream.
newImage = Image.FromStream(ms, true);
}

//set picture for preview
pictureBox1.Image = newImage;
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void frmImagesStore_Load(object sender, EventArgs e)
{

}
//Download the image from DB
private void btnDownload_Click(object sender, EventArgs e)
{
byte[] file = (byte[])dataGridView1.Rows[i].Cells["ImageData"].Value;
string fileName = "image" + i +".gif";
string filePath = System.Environment.CurrentDirectory + "\\Download\\ "+fileName;
FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(file);
bw.Flush();
bw.Close();
int j = i + 1;
MessageBox.Show("Download of image"+" "+j+" " +"is in"+" "+filePath+" "+ "was completed");
}

}
}





//this form used to store new image to DB
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace StoreImagesInSQLServer
{
public partial class frmNewImage : Form
{
public frmNewImage()
{
InitializeComponent();
}

private void cmdSave_Click(object sender, EventArgs e)
{
try
{
//Read Image Bytes into a byte array
byte[] imageData = ReadFile(txtImagePath.Text);

//Initialize SQL Server Connection
SqlConnection CN = new SqlConnection(txtConnectionString.Text);

//Set insert query to save image to DB
string qry = "insert into ImagesStore (OriginalPath,ImageData) values(@OriginalPath, @ImageData)";

//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("@OriginalPath", (object)txtImagePath.Text));
SqlCom.Parameters.Add(new SqlParameter("@ImageData", (object)imageData));

//Open connection and execute insert query.
CN.Open();
SqlCom.ExecuteNonQuery();
CN.Close();
//Close form and return to list or images.
this.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

private void cmdBrowse_Click(object sender, EventArgs e)
{
//Ask user to select file.
OpenFileDialog dlg = new OpenFileDialog();
DialogResult dlgRes = dlg.ShowDialog();
if (dlgRes != DialogResult.Cancel)
{
//Set image in picture box for preview
pictureBox1.ImageLocation = dlg.FileName;

//Provide file path in txtImagePath text box.
txtImagePath.Text = dlg.FileName;
}
}

//Open file in to a filestream and read data in a byte array.
byte[] ReadFile(string sPath)
{
//Initialize byte array with a null value initially.
byte[] data = null;

//Use FileInfo object to get file size.
FileInfo fInfo = new FileInfo(sPath);
long numBytes = fInfo.Length;

//Open FileStream to read file
FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

//Use BinaryReader to read file stream into byte array.
BinaryReader br = new BinaryReader(fStream);

//When you use BinaryReader, you need to supply number of bytes to read from file.
//In this case we want to read entire file. So supplying total number of bytes.
data = br.ReadBytes((int)numBytes);
return data;
}

private void cmdCancel_Click(object sender, EventArgs e)
{
//Close this form if user clicks cancel.
this.Close();
}
}
}


Comments

Author: Arvind Bhardwaj18 May 2012 Member Level: Silver   Points : 0

thanks for article



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: