This code shows how to save image in sql server
// Place a Open file dialog and place two buttons namely find and save //In the find button write the following code private void btnFind_Click(object sender, EventArgs e) { openFileDialog1.Title = "Set Image File"; openFileDialog1.Filter = "Bitmap Files|*.bmp|Gif Files|*.gif|JPEG Files|*.jpg"; openFileDialog1.DefaultExt = "bmp"; openFileDialog1.FilterIndex = 1; openFileDialog1.FileName = ""; if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) { } string sFilePath = ""; sFilePath = openFileDialog1.FileName; if (sFilePath == "") { } if (System.IO.File.Exists(sFilePath) == false) { } else { txtImageFile.Text = sFilePath; mImageFilePath = sFilePath; } }
//In the Save button write the following code private void btnSave_Click(object sender, EventArgs e) { try { if (this.txtImageFile.Text == string.Empty || this.txtTitle.Text == string.Empty) MessageBox.Show("Complete Both the form fields before Submitting","Missing Values",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "File Test Error"); } FileStream fs = new FileStream(mImageFilePath.ToString(),FileMode.Open); byte[] img = new byte[(int)fs.Length]; fs.Read(img, 0, img.Length); fs.Close(); mImageFile = Image.FromFile(mImageFilePath.ToString()); int imgHeight = mImageFile.Height; int imgWidth = mImageFile.Width; int imgLength = mImageFile.PropertyItems.Length; string imgType = Path.GetExtension(mImageFilePath); mImageFile = null; string strConnect; strConnect = "Server=.;uid=sa;pwd=welcome;Initial Catalog=ImageGallery"; SqlConnection conn = new SqlConnection(strConnect); string sSQL = "INSERT INTO ImageCollection(ImageContent, " + "ImageTitle,ImageType,ImageHeight,ImageWidth) VALUES(" + "@pic,@title,@itype,@iheight,@iwidth)"; SqlCommand cmd = new SqlCommand(sSQL, conn); //image SqlParameter pic = new SqlParameter("@pic", SqlDbType.Image); pic.Value = img; cmd.Parameters.Add(pic); //title SqlParameter title = new SqlParameter("@title", SqlDbType.VarChar, 50); title.Value = txtTitle.Text.ToString(); cmd.Parameters.Add(title); //type SqlParameter itype = new SqlParameter("@itype", SqlDbType.Char, 4); itype.Value = imgType.ToString(); cmd.Parameters.Add(itype); fs.Close(); //height SqlParameter height = new SqlParameter("@iheight", SqlDbType.Int, 4); height.Value = imgHeight; cmd.Parameters.Add(height); //width SqlParameter width= new SqlParameter("@iwidth", SqlDbType.Int, 4); width.Value = imgWidth; cmd.Parameters.Add(width); try { conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); MessageBox.Show("Image Loaded Successfully"); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString(), "Data Error"); } }
|
No responses found. Be the first to respond and make money from revenue sharing program.
|