在ms访问数据库中保存/插入图像

时间:2015-11-17 17:53:05

标签: vb.net

我有一个图片框和两个按钮(浏览并保存图像)。用户单击浏览按钮后,用户将从计算机浏览图片,然后通过单击保存按钮将其保存到数据库。

你知道怎么做吗?

2 个答案:

答案 0 :(得分:0)

这是代码,希望它有所帮助:

Imports System.Data.OleDb
Public Class Form1
    Dim cn As New OleDbConnection("Provider = Microsoft.Jet.OleDb.4.0;Data Source = " & Application.StartupPath & "\database.mdb;")
    Dim cm As New OleDbCommand

    Dim bytImage() As Byte
    Private Sub Browse_Click(sender As Object, e As EventArgs) Handles Browse.Click
        Dim dialog As New OpenFileDialog()
        dialog.Title = "Browse Picture"
        dialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
        If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
            PictureBox1.Image = Image.FromFile(dialog.FileName)
        End If
    End Sub

    Private Sub Save_Click(sender As Object, e As EventArgs) Handles Save.Click
        Try
            Dim ms As New System.IO.MemoryStream
            Dim bmpImage As New Bitmap(PictureBox1.Image)

            bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
            bytImage = ms.ToArray()
            ms.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        cn.Open()
        cm.Connection = cn
        cm.CommandType = CommandType.Text
        cm.CommandText = "INSERT INTO `table` (pic) VALUES (@image)"
        cm.Parameters.AddWithValue("@image", bytImage)
        cm.ExecuteNonQuery()
        cn.Close()
    End Sub
End Class

答案 1 :(得分:0)

'' ----在msaccess中保存数据新的accdb msaccess 2007&以上 Imports System.Data.OleDb 公共类Form2     Dim cn As New OleDbConnection(" Provider = Microsoft.ACE.OLEDB.12.0; Data Source ="& Application.StartupPath&" \ acordv.accdb;")     Dim cm As New OleDbCommand

Dim bytImage() As Byte


Private Sub btnbrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrowse.Click
    Dim dialog As New OpenFileDialog()
    dialog.Title = "Browse Picture"
    dialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
    If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
        PictureBox1.Image = Image.FromFile(dialog.FileName)
    End If
End Sub

Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
    Try
        Dim ms As New System.IO.MemoryStream
        Dim bmpImage As New Bitmap(PictureBox1.Image)

        bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
        bytImage = ms.ToArray()
        ms.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    cn.Open()
    cm.Connection = cn
    cm.CommandType = CommandType.Text
    cm.CommandText = "INSERT INTO `pic1` (pic) VALUES (@image)"
    cm.Parameters.AddWithValue("@image", bytImage)
    cm.ExecuteNonQuery()
    cn.Close()
    MsgBox("Image Saved.")
End Sub