Wednesday, February 18, 2009

Load image into Database with VB.Net

    Dim Archive As SqlConnection
    Archive = New SqlConnection
    Archive.ConnectionString = "connection string"
    

Private Sub btnFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFile.Click
    OpenFileDialog1.Filter = "BMP - Bitmap Windows | *.bmp | " _
    & "GIF - CompuServe Graphics Interchange | *.gif | JPG - " _
    & "Compatibile JFIF | *.jpg"
    OpenFileDialog1.Title = "Select image..."
    OpenFileDialog1.ShowDialog()
    If OpenFileDialog1.FileName <> "" Then
         TextBox1.Text = OpenFileDialog1.FileName.ToString
         PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName.ToString)
    End If
End Sub

Private Function ImageToStream()As Byte ()
    Dim Image As New Bitmap(TextBox1.Text)
    Dim stream As MemoryStream = New MemoryStream()
    Image.Save(stream, _
    System.Drawing.Imaging.ImageFormat.Bmp)
    Return stream.ToArray()
End Function

Private Sub Load()
    If File.Exists(TextBox1.Text) Then
         Dim Query As String
        Query = "INSERT INTO Album (Foto) VALUES (@Img)"
        Dim mycommand As New SqlCommand(Query, Archive)
        Archive.Open()
        Dim param As SqlParameter = New SqlParameter("@Img", SqlDbType.Binary)
        param.Value = ImageToStream()
        mycommand.Parameters.Add(param)
        mycommand.ExecuteNonQuery()
        mycommand = Nothing
        Archive.Close()
        PictureBox1.Image = Nothing
        TextBox1.Text = ""
    Else
        MessageBox.Show("File not found!!" , ""Test DB Image", _
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation, _
            MessageBoxDefaultButton.Button1, _
            MessageBoxOptions.DefaultDesktopOnly)
    End If
End Sub

No comments: