mercoledì 18 febbraio 2009

Caricare un'immagine in Database con VB.Net

    Dim Archivio As SqlConnection
    Archivio = New SqlConnection
    Archivio.ConnectionString = "stringa di connessione"
    

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 = "Seleziona l'immagine da caricare ..."
    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 Carica()
    If File.Exists(TextBox1.Text) Then
         Dim Query As String
        Query = "INSERT INTO Album (Foto) VALUES (@Img)"
        Dim comando As New SqlCommand(Query, Archivio)
        Archivio.Open()
        Dim param As SqlParameter = New SqlParameter("@Img", SqlDbType.Binary)
        param.Value = ImageToStream()
        comando.Parameters.Add(param)
        comando.ExecuteNonQuery()
        comando = Nothing
        Archivio.Close()
        PictureBox1.Image = Nothing
        TextBox1.Text = ""
    Else
        MessageBox.Show("File inesistente!!" , ""Test DB Image", _
            MessageBoxButtons.OK, MessageBoxIcon.Exclamation, _
            MessageBoxDefaultButton.Button1, _
            MessageBoxOptions.DefaultDesktopOnly)
    End If
End Sub

Nessun commento: