Direkt zum Hauptbereich

Saving an Image to Database



 Step1 : Show OpenFileDialog

OpenFileDialog strGetImage = new OpenFileDialog();
            strGetImage.InitialDirectory = strDirectory;
            strGetImage.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";
            strGetImage.FilterIndex = 1;
            strGetImage.Multiselect = false;
            strGetImage.RestoreDirectory = true;
            DialogResult Result = strGetImage.ShowDialog();

      Step2: After selecting the image convert the image into Bytes.

            if (Result == DialogResult.OK)
            {
                 strImageLocation = strGetImage.FileName;              

                 byte[] data;
                 Image image = System.Drawing.Image.FromFile(strImageLocation);

                 using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                 {
                     image.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                     data = stream.ToArray(); // Save image into byte.
                 }


             Step3 : Save it to database & return GUID (Primary key) 

              // Create SQL Connection
              SqlConnection con = new SqlConnection();  
              con.ConnectionString = ConfigurationManager.AppSettings["ConnectionString"].ToString();                                

                       // //Stored procedure to insert image
              SqlCommand cmd = new SqlCommand("InsertImage", con);
              cmd.CommandType = CommandType.StoredProcedure;


              SqlParameter Image= new SqlParameter
                              ("@Image", SqlDbType.Image, data.Length);
              Image.Value = data;
              cmd.Parameters.Add(Image);
                 

              con.Open();

Step 4: Convert the returned value into GUID.      
              Guid newId = (Guid)cmd.ExecuteScalar();
              con.Close();      

            } // Select Image OK ends here

Kommentare

Beliebte Posts aus diesem Blog

How to - Web browser Control

 Creating a simple HTML Editor using Web brower control Create a basic Winform Appln. Drag a Webbrowser( end in the list ) from Toolbox. To  create buttons drag a Toolstrip control (near webbrowser ctrl in the list 'Commoncontrols' ) from Toolbox. You can add buttons, text box, progressbar etc by clicking. c   To make the Web browser control editable you have to write the following code while initializing.   InitializeComponent();    webBrowser1.DocumentText = "<HTML><BODY contentEditable='true'></BODY></HTML>";                      toolStripComboFontSize.SelectedIndex = 2; Double click on buttons to generate events. Variable possibilities are there . Some are given below, 1. Change text color  if (colorDialog1.ShowDialog() == DialogResult.OK)           ...