Skip to content

Instantly share code, notes, and snippets.

@arn-ob
Last active August 19, 2016 07:19
Show Gist options
  • Save arn-ob/3f2942ceb31543808f09f8ff1c3cf4d6 to your computer and use it in GitHub Desktop.
Save arn-ob/3f2942ceb31543808f09f8ff1c3cf4d6 to your computer and use it in GitHub Desktop.
C# : Get image from a location and show it to a picture box . And also store it to the database (Win form)
// Get image and show it to the picture Box.......................................
OpenFileDialog fop = new OpenFileDialog();
fop.InitialDirectory = @"C:\";
fop.Filter = "[JPG,JPEG]|*.jpg";
if (fop.ShowDialog() == DialogResult.OK)
{
FileStream FS = new FileStream(@fop.FileName, FileMode.Open, FileAccess.Read);
byte[] img = new byte[FS.Length];
FS.Read(img, 0, Convert.ToInt32(FS.Length));
MemoryStream stream = new MemoryStream(img);
Image RetImage = Image.FromStream(stream);
pictureBox1.Image = RetImage;
}
// Store image to DB ................................................................................
OpenFileDialog fop = new OpenFileDialog();
fop.InitialDirectory = @"C:\";
fop.Filter = "[JPG,JPEG]|*.jpg";
if (fop.ShowDialog() == DialogResult.OK)
{
FileStream FS = new FileStream(@fop.FileName, FileMode.Open, FileAccess.Read);
byte[] img = new byte[FS.Length];
FS.Read(img, 0, Convert.ToInt32(FS.Length));
if (con.State == ConnectionState.Closed)
con.Open();
SqlCommand cmd = new SqlCommand("SaveImage", con);
cmd.CommandType = CommandType.StoredProcedure; // Store Procedure cmd
cmd.Parameters.Add("@img", SqlDbType.Image).Value = img;
cmd.ExecuteNonQuery();
// loadImageIDs();
MessageBox.Show("Image Save Successfully!!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
Get image From DB..............................................................
SqlConnection con = new SqlConnection(DBHandler.GetConnectionString());
SqlCommand cmd = new SqlCommand("ReadImage", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@imgId", SqlDbType.Int).Value =
Convert.ToInt32(cmbImageID.Text.ToString());
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
if (con.State == ConnectionState.Closed)
con.Open();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["ImageData"]);
picImage.Image = Image.FromStream(ms);
picImage.SizeMode = PictureBoxSizeMode.StretchImage;
picImage.Refresh();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
///////////////////////////////////////////////
@arn-ob
Copy link
Author

arn-ob commented Jul 21, 2016

Where the display image code ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment