Sunday, September 10, 2017

C# windows application image upload

First open visual studio File->New->Project->Windows Forms Application-> Ok












Then we use toolbox for design the input field and button and other.












Click the insert button and paste the code.

          private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs1 = new FileStream(textBox1.Text, System.IO.FileMode.Open,  System.IO.FileAccess.Read);
            byte[] image = new byte[fs1.Length];
            fs1.Read(image, 0, Convert.ToInt32(fs1.Length));
            fs1.Close();

            SqlConnection con = new SqlConnection("Data Source=VTG-IT-D20;Initial Catalog=testo;Integrated Security=True;");
            con.Open();
            SqlCommand cmd = new SqlCommand("Insert into Image (Id,Photo) Values ('1',@Pic)",con);
            SqlParameter prm = new SqlParameter("@Pic", SqlDbType.VarBinary, image.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, image);
            cmd.Parameters.Add(prm);


            cmd.ExecuteNonQuery();
            con.Close();
        }

Click the view button and paste the code.

SqlConnection con = new SqlConnection("Data Source=VTG-IT-D20;Initial Catalog=testo;Integrated Security=True;");
            con.Open();

            SqlDataAdapter s = new SqlDataAdapter("select * From Image Where b = '" +   textBox2.Text + "' ", con);
            DataTable dt = new DataTable();

            s.Fill(dt);
            byte[] Mydata = new byte[0];
            Mydata = (byte[])dt.Rows[0][1];
            MemoryStream str = new MemoryStream(Mydata);
            pictureBox1.Image = Image.FromStream(str);

create a table in a SQL server.in this project database name ‘testo’.

CREATE TABLE [dbo].[Image](
       [Id] [int] NULL,
       [Photo] [image] NULL,
       [b] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Image] PRIMARY KEY CLUSTERED
(
       [b] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

Then we save the code. Now click on start for execute the code. This window comes.
Click upload and insert image.












If you want to see the insert image then give the id of the image and click view.




No comments:

Post a Comment