Senin, 20 Desember 2010

Store image in SQL Database using vb.net

Create a table called ImagesStore.

CREATE TABLE ImagesStore (ImageId int IDENTITY (1, 1) NOT NULL ,OriginalPath varchar (200)  NOT NULL ,ImageData image NOT NULL)     
2). Then the main code is written in vb.net . Bellow code is use to convert the image into byte and the send it to the database to store.
Convert the image and send it to database:
01Dim str As String
02        Dim fstream As FileStream
03        Dim imgdata As Byte()
04        Dim data As Byte()
05        Dim finfo As FileInfo
06        finfo = New FileInfo(TextBox3.Text)
07        Dim numbyte As Long
08        Dim br As BinaryReader
09        numbyte = finfo.Length
10        fstream = New FileStream(TextBox3.Text, FileMode.Open, FileAccess.Read)
11        br = New BinaryReader(fstream)
12        data = br.ReadBytes(numbyte)
13        imgdata = data
14        con = New SqlConnection(TextBox1.Text)
15        con.Open()
16        str = "insert into ImagesStore (OriginalPath,ImageData) values(@op, @i)"
17        cmd = New SqlCommand(str, con)
18        cmd.Parameters.Add(New SqlParameter("op", SqlDbType.Char, 200))
19        cmd.Parameters("op").Value = TextBox1.Text
20        cmd.Parameters.Add(New SqlParameter("i", SqlDbType.Image))
21        cmd.Parameters("i").Value = imgdata
22        cmd.ExecuteNonQuery()
23        MsgBox("Image Inserted In DataBase..", MsgBoxStyle.Information)
24        Me.Close()
25End Sub
3). to retrieve the image from the database and display in the Picture Box .below code is responsible for display the picture in picture box. The main function of code is to retrieve the data in bytes and convert it to a normal image and display it.
01Dim imagedata As Byte()
02        Try
03            PictureBox1.Location = New Point(3, 3)
04            Timer1.Enabled = False
05            imagedata = (DataGridView1.Rows(e.RowIndex).Cells("ImageData").Value)
06            Dim ms As MemoryStream
07            ms = New MemoryStream(imagedata, 0, imagedata.Length)
08            ms.Write(imagedata, 0, imagedata.Length)
09            Dim im As Image
10            im = Image.FromStream(ms, True)
11            PictureBox1.Image = im
12        Catch ex As Exception
13            Timer1.Enabled = True
14        End Try

Tidak ada komentar:

Posting Komentar