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();
}
}
This was a very clear and practical walkthrough—thank you for explaining how to save images from a PictureBox directly into a database. The step-by-step approach makes it easy to follow, and the code snippets are especially helpful for beginners working with C# and Windows Forms.
ReplyDeleteI appreciate that you addressed both the conversion process and the database storage side—it really ties the workflow together. Posts like this are invaluable for developers who want to understand not just the “how” but also the “why” behind the implementation.
Looking forward to more tutorials like this!
Discover how the anti-inflammation diet can transform your health—read more at
Visit Keto For India