Save Image to MS-SQL Server 2000 Database with Microsoft Visual Basic 2005

1- Create Database in MS-SQL Server 2000 (example)
–  Create one table named: tbltest
CREATE TABLE tbltest(photo image)

2- Create Project in Visual Basic 2005 or Visual Basic 2008
–  Create one form named: frmtest
–  Add picture control to frmtest with named: picImage
–  Add button Browse under the picture control
–  Add button Save under the Browse button
–  Add button Get near button Save
–  When click Browse button you code to get file image to picture control

Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
Me.ofdBrowse.Filter = "Images (*.jpg,*.bmp)|*.jpg;*.bmp"
      If Me.ofdBrowse.ShowDialog() = Windows.Forms.DialogResult.OK Then
        Me.picImage.Image = System.Drawing.Image.FromFile(Me.ofdBrowse.FileName)
      End If
End Sub

– When click button Save (save image to tbltest in database)
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim myMS As New IO.MemoryStream
Dim arrImage() As Byte
Dim strImage As String = ""

If Not IsNothing(Me.picImage.Image) Then
   Me.picImage.Image.Save(myMS, Me.picImage.Image.RawFormat)
   arrImage = myMS.GetBuffer
   strImage = "@Image"
Else
   arrImage = Nothing
   strImage = "NULL"
End If

Dim cmd As New SqlClient.SqlCommand
cmd.Connection = Cnn 'cnn is a connection you have connect to database with the tbltest in it
cmd.CommandText = "INSERT INTO tbltest(photo) " & _
                  " VALUES(" & strImage & ")"
'if image is not nothing
If strImage = "@Image" Then
   cmd.Parameters.Add(strImage, SqlDbType.Image).Value = arrImage
End If
cmd.ExecuteNonQuery()
cmd.dispose()
End Sub

– When click button Get (save image back from database – the top one)
Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGet.Click
Dim da As New SqlClient.SqlDataAdapter("SELECT TOP 1 photo FROM tbltest ", Cnn)
Dim dt As New DataTable
Dim arrImage() As Byte
Dim myMS As New IO.MemoryStream
da.Fill(dt)
If Not IsDBNull(dt.Rows(0).Item("photo")) Then
arrImage = dt.Rows(0).Item("photo")
For Each ar As Byte In arrImage
myMS.WriteByte(ar)
Next
Me.picImage.Image = System.Drawing.Image.FromStream(myMS)
End If
End Sub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: