http://codebind.blogspot.com/ https://www.youtube.com/user/codesonfire Skype: mijanashik Email:
[email protected]
Project Name: C#.NET Save and Retrieve Image From Database
using using using using using using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Threading.Tasks; System.Windows.Forms; System.Data.SqlClient; System.IO; System.Configuration;
namespace CodeBind { public partial class frmImageSave : Form { public frmImageSave() { InitializeComponent(); } public static string GenerateString() { string returnValue = null; // Look for the name in the connectionStrings section. ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["CodeBind.Properties.Settings.CodeBindConnectionSt ring"]; //If found, return the connection string. if (settings != null) returnValue = settings.ConnectionString;
return returnValue; //return ConfigurationManager.AppSettings["ConnString"].ToString(); } private void btnSave_Click(object sender, EventArgs e) { string connString = GenerateString(); if (MessageBox.Show("Do you want to save this image to database?", "Confirmation") == DialogResult.No) return; try { SqlConnection Conn = new SqlConnection(connString); if (Conn.State == ConnectionState.Closed) { Conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = Conn; Cursor = Cursors.WaitCursor; byte[] img = null; FileStream fs = new FileStream(@txtImagePath.Text, FileMode.Open, FileAccess.Read); BinaryReader br = new BinaryReader(fs); img = br.ReadBytes((int)fs.Length); string sql = "INSERT INTO SavedImages(ImageName,ImageData, OriginalPath) VALUES('"+ txtFileName.Text +"',@IMG,'" + txtImagePath.Text + "')"; cmd.CommandText = sql; cmd.Parameters.Add(new SqlParameter("@IMG", img)); cmd.ExecuteNonQuery(); Conn.Close(); Cursor = Cursors.Default; MessageBox.Show("Image saved to database.", "Saved!"); LoadImageNames(); } catch (Exception ex) { MessageBox.Show(ex.Message); Cursor = Cursors.Default; } }
private void frmImageSave_Load(object sender, EventArgs e) { LoadImageNames(); } private void LoadImageNames() { try { string connString = GenerateString();
SqlConnection Conn = new SqlConnection(connString); if (Conn.State == ConnectionState.Closed) { Conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = Conn; Cursor = Cursors.WaitCursor; listImageName.Items.Clear(); cmd.CommandText = "SELECT ImageName FROM SAVEDIMAGES ORDER BY ImageName"; SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { listImageName.Items.Add(reader[0].ToString()); } reader.Close(); Conn.Close(); Cursor = Cursors.Default; } catch (Exception ex) { MessageBox.Show(ex.Message); Cursor = Cursors.Default; } } private void bthShow_Click(object sender, EventArgs e) { SqlConnection Conn = new SqlConnection(GenerateString()); if (Conn.State == ConnectionState.Closed) { Conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = Conn; try { SqlDataReader reader; cmd.CommandText = "SELECT ImageData FROM SavedImages where ImageName='" + listImageName.Text + "'"; reader = cmd.ExecuteReader(); while (reader.Read()) { GetImage(pictureBox1, (byte[])reader["ImageData"]); } reader.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public static void GetImage(PictureBox PictureImage, Byte[] ImageValue) { try {
byte[] imageData = (byte[])ImageValue; //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 PictureImage.Image = newImage; //return PictureImage; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } private void listImageName_SelectedIndexChanged(object sender, EventArgs e) { bthShow_Click(sender, e); } private void btnDelete_Click(object sender, EventArgs e) { if (MessageBox.Show("Do you want to delete this image?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No) return; try { SqlCommandExecute("DELETE FROM SavedImages WHERE ImageName ='" + listImageName.Text + "'"); MessageBox.Show("Image deleted successfully.","Deleted"); frmImageSave_Load(sender, e); } catch(Exception ex) { MessageBox.Show(ex.Message); } } private void SqlCommandExecute( string sqlcode) { SqlConnection Conn = new SqlConnection(GenerateString()); if (Conn.State == ConnectionState.Closed) { Conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = Conn; cmd.CommandText = sqlcode;
cmd.ExecuteNonQuery(); } private static SqlDataReader DataReader(string sqlcode) { SqlConnection Conn = new SqlConnection(GenerateString()); if (Conn.State == ConnectionState.Closed) { Conn.Open(); } SqlCommand cmd = new SqlCommand(); cmd.Connection = Conn; SqlDataReader reader; cmd.CommandText = sqlcode; reader = cmd.ExecuteReader(); return reader; } private void btnBrowse_Click(object sender, EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); //dlg.InitialDirectory = ""; dlg.Filter = "Image File (*.jpg;*.bmp;*.png;)|*.jpg;*.bmp;*.png;"; DialogResult dlgRes = dlg.ShowDialog(); if (dlgRes != DialogResult.Cancel) { //Set image in picture box pictureBox1.ImageLocation = dlg.FileName; //Provide file path in txtImagePath text box. txtImagePath.Text = dlg.FileName; txtFileName.Text = dlg.SafeFileName; } } } }