Kamis, 16 Desember 2010

Bagaimana MengInsert gambar kedalam Table
















Tahap pertama adalah dengan membuat form seperti gambar diatas, dan jangan lupa tambahkan 4 button, 1 textbox, OpenfileDialog dan Picturebox.
Di asumsikan kita memiliki table dengan nama TbPic dengan field (ID dan Pic). Sekarang kita masuk ke coding.
Untuk menampilkan file gambar kedalam Picture box ikuti sintaks berikut.
OFD.Filter = "Image Files (*.jpg, *.bmp, *.gif, *.png)*.jpg; *.bmp; *.gif; *.png"
OFD.ShowDialog()
txtFileName.Text = OFD.FileName
txtFileName.SelectionStart = txtFileName.Text.Length
If Trim(txtFileName.Text) <> "" Then
PicBox.Image = Image.FromFile(txtFileName.Text)
End If
Ikuti sintaks dibawah untuk memasukkan gambar kedalam table.
Try
Dim ms As New System.IO.MemoryStream()
PicBox.Image.Save(ms, PicBox.Image.RawFormat)
Dim CPic() As Byte = ms.GetBuffer
ms.Close()

Dim MyConnection As AccessData.DataBaseConnection = New AccessData.DataBaseConnection

Dim myCommand As SqlCommand = New SqlCommand("Insert Into TbPic (ID,Pic) values (@ID,@Pic)", MyConnection.open)

myCommand.CommandType = CommandType.Text

Dim parameterID As SqlParameter = New SqlParameter("@ID", SqlDbType.VarChar)
parameterID.Value = "1"

Dim parameterPic As SqlParameter = New SqlParameter("@Pic", SqlDbType.Image)
parameterPic.Value = CPic
With myCommand.Parameters
.Add(parameterID)
.Add(parameterPic)
End With
Dim result As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)


Catch ex As Exception
MsgBox(ex.Message)
Finally
MyConnection.close()
End Try

Lalu bagaimana caranya untuk menampilkan kembali tersebut ke dalam picture box. Berikut sintaks nya
Try
Dim arr() As Byte

objCommand = MyConnection.open.CreateCommand
objCommand.CommandText = ("select Pic from TbPic;")
objdatareader = objCommand.ExecuteReader
objdatareader.Read()
arr = objdatareader.Item("Pic")
PicBox.Image = Image.FromStream(New IO.MemoryStream(arr))
Catch ex As Exception
MsgBox(ex.Message)
Finally
MyConnection.close()
End Try

Tidak ada komentar:

Posting Komentar