1. create table in database
CREATE TABLE [dbo].[tbl_Image_Data] (
[ID] [int] NOT NULL ,
[Name] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[Picture] [image] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
2. add picturebox and name it pb and two buttons "browse" and "save"
3. First of all browse image from computer to pictureBox
private void btnBrowse_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();
// openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
openFileDialog.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";
if (openFileDialog.ShowDialog(this) == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog.OpenFile()) != null)
{
string FileName = openFileDialog.FileName;
txtImagepath.Text = FileName;
if (myStream.Length > 512000)
{
MessageBox.Show("File size limit exceed");
}
else
{
//pb is my pictureBox name load image in pb
pb.Load(FileName);
//stretch image to fit in picturebox
pb.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
}
//MessageBox.Show(myStream.Length.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. error: " + ex.Message);
}
}
}
2.save this to sql server
private void btnSave_Click(object sender, EventArgs e)
{
MemoryStream stream = new
MemoryStream();
pb.Image.Save(stream, ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
byte_Img=pic;
}
try
{
this.sqlConnection1.Open();
if (sqlCommand1.Parameters.Count == 0)
{
this.sqlCommand1.CommandText = "INSERT INTO tbl_Image_Data(ID," +
" Name,Picture) values(@ID,@Name,@Picture)";
this.sqlCommand1.Parameters.Add("@ID",
System.Data.SqlDbType.Int, 4);
this.sqlCommand1.Parameters.Add("@Name",
System.Data.SqlDbType.VarChar, 50);
this.sqlCommand1.Parameters.Add("@Picture",
System.Data.SqlDbType.Image);
}
this.sqlCommand1.Parameters["@ID"].Value = this.ID.Text;
this.sqlCommand1.Parameters["@Name"].Value = this.Name.Text;
this.sqlCommand1.Parameters["@Picture"].Value = this.byte_Img;
int result = this.sqlCommand1.ExecuteNonQuery();
MessageBox.Show(Convert.ToString(result));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
this.sqlConnection1.Close();
}
}